Skip to content

Commit

Permalink
feat: shouldretry function
Browse files Browse the repository at this point in the history
  • Loading branch information
kukhariev committed May 6, 2021
1 parent 637e258 commit 445d7b0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
10 changes: 9 additions & 1 deletion src/uploadx/lib/retry-handler.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ErrorType, RetryHandler } from './retry-handler';
import { ErrorType, RetryHandler, ShouldRetryFunction } from './retry-handler';

describe('ErrorHandler', () => {
it('ErrorHandler.kind(status)', () => {
Expand All @@ -11,4 +11,12 @@ describe('ErrorHandler', () => {
expect(errorHandler.kind(404)).toBe(ErrorType.NotFound);
expect(errorHandler.kind(401)).toBe(ErrorType.Auth);
});

it('Custom shouldRetry', () => {
const shouldRetry: ShouldRetryFunction = (c, a = 0) => c === 500 && a < 2;
const errorHandler = new RetryHandler({ shouldRetry });
expect(errorHandler.kind(500)).toBe(ErrorType.Retryable);
errorHandler.attempts = 3;
expect(errorHandler.kind(500)).toBe(ErrorType.Fatal);
});
});
9 changes: 8 additions & 1 deletion src/uploadx/lib/retry-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ export enum ErrorType {
Fatal
}

export type ShouldRetryFunction = (code: number, attempts?: number) => boolean;

export interface RetryConfig {
/** Maximum number of retry attempts */
maxAttempts?: number;
Expand All @@ -14,6 +16,8 @@ export interface RetryConfig {
authErrorCodes?: number[];
/** Retryable 4xx status codes */
shouldRetryCodes?: number[];
/** Overrides the built-in function that determines whether the operation should be repeated */
shouldRetry?: ShouldRetryFunction;
minDelay?: number;
maxDelay?: number;
}
Expand All @@ -23,6 +27,9 @@ const defaultRetryConfig: Required<RetryConfig> = {
shouldRestartCodes: [404, 410],
authErrorCodes: [401],
shouldRetryCodes: [423, 429],
shouldRetry(code: number): boolean {
return code < 400 || code >= 500 || this.shouldRetryCodes.indexOf(code) !== -1;
},
minDelay: 500,
maxDelay: 50000
};
Expand Down Expand Up @@ -50,7 +57,7 @@ export class RetryHandler {
if (this.config.shouldRestartCodes.indexOf(code) !== -1) {
return ErrorType.NotFound;
}
if (code < 400 || code >= 500 || this.config.shouldRetryCodes.indexOf(code) !== -1) {
if (this.config.shouldRetry(code, this.attempts)) {
return ErrorType.Retryable;
}
return ErrorType.Fatal;
Expand Down

0 comments on commit 445d7b0

Please sign in to comment.