43 lines
1.3 KiB
TypeScript
43 lines
1.3 KiB
TypeScript
import * as Bluebird from 'bluebird'
|
|
import * as request from 'request'
|
|
import { waitMs } from './core-utils'
|
|
import { CONFIG } from '../initializers/constants'
|
|
|
|
function doRequest <T> (
|
|
requestOptions: request.CoreOptions & request.UriOptions
|
|
): Bluebird<{ response: request.RequestResponse, body: T }> {
|
|
if (!(requestOptions.headers)) requestOptions.headers = {}
|
|
|
|
const webserverUrl = CONFIG.WEBSERVER.SCHEME + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
|
|
requestOptions.headers['User-Agent'] = `PeerTube search index (+${webserverUrl})`
|
|
|
|
return new Bluebird<{ response: request.RequestResponse, body: T }>((res, rej) => {
|
|
request(requestOptions, (err, response, body) => err ? rej(err) : res({ response, body }))
|
|
})
|
|
}
|
|
|
|
async function doRequestWithRetries<T> (
|
|
requestOptions: request.CoreOptions & request.UriOptions,
|
|
maxRetries: number,
|
|
msToWait: number,
|
|
currentRetry = 0
|
|
): Promise<{ response: request.RequestResponse, body: T }> {
|
|
const res = await doRequest<T>(requestOptions)
|
|
|
|
if (res.response.statusCode === 429) {
|
|
if (currentRetry < maxRetries) {
|
|
await waitMs(msToWait)
|
|
return doRequestWithRetries(requestOptions, maxRetries, msToWait, currentRetry + 1)
|
|
}
|
|
|
|
throw new Error('Exceeded max retries for request ' + requestOptions.uri)
|
|
}
|
|
|
|
return res
|
|
}
|
|
|
|
export {
|
|
doRequest,
|
|
doRequestWithRetries
|
|
}
|