undici-retry
Library for handling retry logic with undici HTTP client
Basic example
import { sendWithRetry } from 'undici-retry';
import type { RetryConfig, RequestParams} from 'undici-retry'
import { Client } from 'undici';
import type { Dispatcher } from 'undici';
const client = new Client('http://my-url.com', {})
const request: Dispatcher.RequestOptions = {
method: 'GET',
path: '/',
bodyTimeout: 500,
headersTimeout: 500,
}
const retryConfig: RetryConfig = {
maxAttempts: 3,
delayBetweenAttemptsInMsecs: 100,
statusCodesToRetry: [500, 502, 503],
retryOnTimeout: false,
}
const requestParams: RequestParams = {
safeParseJson: true,
blobBody: false,
throwOnInternalError: true,
}
const result = await sendWithRetry(client, request, retryConfig, requestParams)
if (result.error) {
console.log(JSON.stringify({
body: result.error.body,
headers: result.error.headers,
statusCode: result.error.statusCode,
}))
}
if (result.result) {
console.log(JSON.stringify({
body: result.result.body,
headers: result.result.headers,
statusCode: result.result.statusCode,
}))
}
Delay resolvers
You can write custom logic for resolving the retry delay based on response received. E. g.:
const OFFSET = 100
const response = await sendWithRetry(client, request, {
maxAttempts: 3,
statusCodesToRetry: [429, 502, 503],
delayBetweenAttemptsInMsecs: 30,
retryOnTimeout: false,
delayResolver: (response) => {
if (response.statusCode === 429) {
return 60000 - (now % 60000) + OFFSET
}
if (response.statusCode === 500) {
return -1
}
return undefined
},
})