Skip to content

Commit

Permalink
Expose default retry logic as defaultOptions.onShouldRetry (#637)
Browse files Browse the repository at this point in the history
* 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.
  • Loading branch information
hahn-kev authored Oct 24, 2023
1 parent 64b58d0 commit 3283cb4
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
2 changes: 1 addition & 1 deletion lib/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
13 changes: 11 additions & 2 deletions lib/upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const defaultOptions = {
addRequestId: false,
onBeforeRequest: null,
onAfterResponse: null,
onShouldRetry: null,
onShouldRetry: defaultOnShouldRetry,

chunkSize: Infinity,
retryDelays: [0, 1000, 3000, 5000],
Expand Down Expand Up @@ -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
*
Expand All @@ -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()
}
Expand Down

0 comments on commit 3283cb4

Please sign in to comment.