PeerTube/server/helpers/requests.ts

36 lines
1.1 KiB
TypeScript
Raw Normal View History

2018-01-15 04:10:46 -06:00
import * as Bluebird from 'bluebird'
2017-11-10 07:34:45 -06:00
import { createWriteStream } from 'fs'
2017-11-10 10:27:49 -06:00
import * as request from 'request'
2017-12-28 04:16:08 -06:00
import { ACTIVITY_PUB } from '../initializers'
2018-01-15 02:46:46 -06:00
function doRequest (
requestOptions: request.CoreOptions & request.UriOptions & { activityPub?: boolean }
2018-01-15 03:03:13 -06:00
): Bluebird<{ response: request.RequestResponse, body: any }> {
2017-12-28 04:16:08 -06:00
if (requestOptions.activityPub === true) {
if (!Array.isArray(requestOptions.headers)) requestOptions.headers = {}
requestOptions.headers['accept'] = ACTIVITY_PUB.ACCEPT_HEADER
}
2017-11-09 10:51:58 -06:00
2018-01-15 04:10:46 -06:00
return new Bluebird<{ response: request.RequestResponse, body: any }>((res, rej) => {
2017-11-09 10:51:58 -06:00
request(requestOptions, (err, response, body) => err ? rej(err) : res({ response, body }))
})
}
2016-02-05 11:03:20 -06:00
2017-11-10 07:34:45 -06:00
function doRequestAndSaveToFile (requestOptions: request.CoreOptions & request.UriOptions, destPath: string) {
2018-02-15 11:40:24 -06:00
return new Bluebird<void>((res, rej) => {
const file = createWriteStream(destPath)
file.on('finish', () => res())
2017-11-10 07:34:45 -06:00
request(requestOptions)
.on('error', err => rej(err))
2018-02-15 11:40:24 -06:00
.pipe(file)
2017-11-10 07:34:45 -06:00
})
}
// ---------------------------------------------------------------------------
2016-02-05 11:03:20 -06:00
2017-05-15 15:22:03 -05:00
export {
2017-11-09 10:51:58 -06:00
doRequest,
2017-11-10 10:27:49 -06:00
doRequestAndSaveToFile
2017-05-15 15:22:03 -05:00
}