@defra-fish/connectors-lib
Version:
Shared connectors
79 lines (69 loc) • 2.25 kB
JavaScript
import fetch from 'node-fetch'
import db from 'debug'
import { StatusCodes } from 'http-status-codes'
const debug = db('connectors:http-request-batcher')
export default class HTTPRequestBatcher {
constructor ({ batchSize = 50, delay = 1000 } = {}) {
this.
this.
}
get batchSize () {
return this.
}
get requestQueue () {
return this.
}
get responses () {
return this.
}
get delay () {
return this.
}
addRequest (url, options) {
if (!url) {
throw new Error('URL is required')
}
this.
}
async _sendBatch (fetchRequests, sentRequests, requestQueue) {
const batchResponses = await Promise.all(fetchRequests)
this.
for (let x = 0; x < batchResponses.length; x++) {
const response = batchResponses[x]
if (response.status === StatusCodes.TOO_MANY_REQUESTS && sentRequests[x].attempts < 2) {
requestQueue.push({ ...sentRequests[x], attempts: sentRequests[x].attempts + 1 })
this.
debug(`429 response received for ${sentRequests[x].url}, reducing batch size to ${this.
}
}
fetchRequests.length = 0
sentRequests.length = 0
if (requestQueue.length) {
// don't wait if this is the last batch
await new Promise(resolve => setTimeout(resolve, this.
}
}
async fetch () {
debug(
`Beginning batched fetch of ${this.
this.
} and delay between batches of ${this.
)
const requestQueue = [...this.
const sentRequests = []
const fetchRequests = []
while (requestQueue.length) {
const request = requestQueue.shift()
fetchRequests.push(fetch(request.url, request.options))
sentRequests.push({ attempts: 1, ...request })
if (fetchRequests.length === this.
await this._sendBatch(fetchRequests, sentRequests, requestQueue)
}
}
debug('Batched fetch complete')
}
}