From 3283cb4020543b9dd8d74320b5d96bca7920eb10 Mon Sep 17 00:00:00 2001 From: Kevin Hahn Date: Tue, 24 Oct 2023 03:44:21 -0600 Subject: [PATCH] Expose default retry logic as `defaultOptions.onShouldRetry` (#637) * move default retry logic on to defaultOptions to allow user to reuse it inside custom `onShouldRetry` option * correct onShouldRetry as it'll never be called with just an error * remove unused parameters causing build error * move default on should retry into it's own function. --- lib/index.d.ts | 2 +- lib/upload.js | 13 +++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/lib/index.d.ts b/lib/index.d.ts index 3ddee0f0..5e866729 100644 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -33,7 +33,7 @@ interface UploadOptions { onSuccess?: (() => void) | null onError?: ((error: Error | DetailedError) => void) | null onShouldRetry?: - | ((error: Error | DetailedError, retryAttempt: number, options: UploadOptions) => boolean) + | ((error: DetailedError, retryAttempt: number, options: UploadOptions) => boolean) | null onUploadUrlAvailable?: (() => void) | null diff --git a/lib/upload.js b/lib/upload.js index b38a2aa8..61289da4 100644 --- a/lib/upload.js +++ b/lib/upload.js @@ -23,7 +23,7 @@ const defaultOptions = { addRequestId: false, onBeforeRequest: null, onAfterResponse: null, - onShouldRetry: null, + onShouldRetry: defaultOnShouldRetry, chunkSize: Infinity, retryDelays: [0, 1000, 3000, 5000], @@ -1000,7 +1000,7 @@ function isOnline() { /** * Checks whether or not it is ok to retry a request. - * @param {Error} err the error returned from the last request + * @param {Error|DetailedError} err the error returned from the last request * @param {number} retryAttempt the number of times the request has already been retried * @param {object} options tus Upload options * @@ -1026,6 +1026,15 @@ function shouldRetry(err, retryAttempt, options) { return options.onShouldRetry(err, retryAttempt, options) } + return defaultOnShouldRetry(err) +} + +/** + * determines if the request should be retried. Will only retry if not a status 4xx except a 409 or 423 + * @param {DetailedError} err + * @returns {boolean} + */ +function defaultOnShouldRetry(err) { const status = err.originalResponse ? err.originalResponse.getStatus() : 0 return (!inStatusCategory(status, 400) || status === 409 || status === 423) && isOnline() }