aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/helpers/requests.ts
blob: ce185a2c0248b3999e0902f2c08cb73abaf3956a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import * as Promise from 'bluebird'
import { createWriteStream } from 'fs'
import * as request from 'request'
import { ACTIVITY_PUB } from '../initializers'

function doRequest (requestOptions: request.CoreOptions & request.UriOptions & { activityPub?: boolean }) {
  if (requestOptions.activityPub === true) {
    if (!Array.isArray(requestOptions.headers)) requestOptions.headers = {}
    requestOptions.headers['accept'] = ACTIVITY_PUB.ACCEPT_HEADER
  }

  return new Promise<{ response: request.RequestResponse, body: any }>((res, rej) => {
    request(requestOptions, (err, response, body) => err ? rej(err) : res({ response, body }))
  })
}

function doRequestAndSaveToFile (requestOptions: request.CoreOptions & request.UriOptions, destPath: string) {
  return new Promise<request.RequestResponse>((res, rej) => {
    request(requestOptions)
      .on('response', response => res(response as request.RequestResponse))
      .on('error', err => rej(err))
      .pipe(createWriteStream(destPath))
  })
}

// ---------------------------------------------------------------------------

export {
  doRequest,
  doRequestAndSaveToFile
}