Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add retry count to the response #791

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .prettierrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
"trailingComma": "all",
"singleQuote": true,
"printWidth": 120,
"tabWidth": 4
"tabWidth": 4,
"endOfLine": "auto"
}
26 changes: 21 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,20 @@ export interface FetchRetryParams {
retryOn?: number[] | RetryRequestFunction;
}

export interface RequestResponse extends Response {
retryCount: number;
}

export class RequestError extends Error {
retryCount: number;

constructor(message: string, retryCount: number) {
super(message);
this.name = 'RequestError';
this.retryCount = retryCount;
}
}

function sanitize(params: FetchRetryParams, defaults: Required<FetchRetryParams>): Required<FetchRetryParams> {
const result = { ...defaults, ...params };
if (typeof result.retries === 'undefined') {
Expand All @@ -33,10 +47,10 @@ function sanitize(params: FetchRetryParams, defaults: Required<FetchRetryParams>
export function fetchBuilder<F extends (...args: any) => Promise<any> = typeof fetch>(
fetchFunc: F,
params: FetchRetryParams = {},
): (input: Parameters<F>[0], init?: Parameters<F>[1] & FetchRetryParams) => ReturnType<F> {
): (input: Parameters<F>[0], init?: Parameters<F>[1] & FetchRetryParams) => Promise<RequestResponse> {
const defaults = sanitize(params, { retries: 3, retryDelay: 500, retryOn: [419, 503, 504] });

return function (input: Parameters<F>[0], init?: Parameters<F>[1] & FetchRetryParams): ReturnType<F> {
return function (input: Parameters<F>[0], init?: Parameters<F>[1] & FetchRetryParams): Promise<RequestResponse> {
const frp = sanitize(
{
retries: init?.retries,
Expand Down Expand Up @@ -64,15 +78,17 @@ export function fetchBuilder<F extends (...args: any) => Promise<any> = typeof f
// eslint-disable-next-line @typescript-eslint/no-use-before-define
retry(attempt, null, response);
} else {
resolve(response);
const responseWithRetryCount = response as RequestResponse;
responseWithRetryCount.retryCount = attempt;
resolve(responseWithRetryCount);
}
})
.catch(function (error: Error): void {
if (retryOnFn(attempt, frp.retries, error, null)) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
retry(attempt, error, null);
} else {
reject(error);
reject(new RequestError(error.message, attempt));
}
});
};
Expand All @@ -87,7 +103,7 @@ export function fetchBuilder<F extends (...args: any) => Promise<any> = typeof f
}

extendedFetch(0);
}) as ReturnType<F>;
});
};
}

Expand Down
30 changes: 18 additions & 12 deletions src/test/unit/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Response } from 'node-fetch';
import builder from '../../';
import builder, { RequestError } from '../../';

const mockedFetch = jest.fn();

Expand All @@ -15,7 +15,7 @@ describe('fetch builder', (): void => {
mockedFetch.mockResolvedValueOnce(new Response('504', { status: 504 }));

return expect(f('https://example.test'))
.resolves.toMatchObject({ status: 503 })
.resolves.toMatchObject({ status: 503, retryCount: 0 })
.then((): void => {
expect(mockedFetch.mock.calls.length).toBe(1);
});
Expand All @@ -37,7 +37,7 @@ describe('fetch retry', (): void => {
return expect(f(expectedParam))
.resolves.toEqual(expectedResponse)
.then((): void => {
expect(mockedFetch).toBeCalledWith(expectedParam, undefined);
expect(mockedFetch).toHaveBeenCalledWith(expectedParam, undefined);
});
});

Expand All @@ -61,11 +61,17 @@ describe('fetch retry', (): void => {
const retries = 3;
const f = builder(mockedFetch, { retries, retryDelay: 0 });

return expect(f('https://example.test'))
.rejects.toMatchObject({ message: expectedResponse })
.then((): void => {
expect(mockedFetch.mock.calls.length).toBe(retries + 1);
});
let catchError;
try {
await f('https://example.test');
} catch (error) {
catchError = error;
}

expect(catchError).toMatchObject({ message: expectedResponse, retryCount: 3 });
expect(catchError).toBeInstanceOf(Error);
expect(catchError).toBeInstanceOf(RequestError);
expect(mockedFetch.mock.calls.length).toBe(retries + 1);
});

it('will return the last response if all attempts fail', async (): Promise<void> => {
Expand All @@ -77,7 +83,7 @@ describe('fetch retry', (): void => {
const f = builder(mockedFetch, { retries, retryDelay: 0 });

return expect(f('https://example.test'))
.resolves.toMatchObject({ status: 419 })
.resolves.toMatchObject({ status: 419, retryCount: 2 })
.then((): void => {
expect(mockedFetch.mock.calls.length).toBe(retries + 1);
});
Expand All @@ -94,7 +100,7 @@ describe('fetch retry', (): void => {
const f = builder(mockedFetch, { retries, retryDelay: 0 });

return expect(f('https://example.test'))
.resolves.toMatchObject({ status: 200 })
.resolves.toMatchObject({ status: 200, retryCount: 3 })
.then((): void => {
expect(mockedFetch.mock.calls.length).toBe(4);
});
Expand All @@ -110,7 +116,7 @@ describe('fetch retry', (): void => {
mockedFetch.mockResolvedValueOnce(new Response('504', { status: 504 }));
mockedFetch.mockResolvedValueOnce(new Response('419', { status: 419 }));
return expect(f('https://example.test', { retries: 2, retryDelay: 0, retryOn: [419, 503, 504] }))
.resolves.toMatchObject({ status: 419 })
.resolves.toMatchObject({ status: 419, retryCount: 2 })
.then((): void => {
expect(mockedFetch.mock.calls.length).toBe(3);
expect(delayFn.mock.calls.length).toBe(0);
Expand All @@ -133,7 +139,7 @@ describe('fetch retry', (): void => {
mockedFetch.mockResolvedValueOnce(new Response('200', { status: 200 }));

return expect(f('https://example.test', { retries: 3, retryDelay: delayFn, retryOn: retryFn }))
.resolves.toMatchObject({ status: 504 })
.resolves.toMatchObject({ status: 504, retryCount: 1 })
.then((): void => {
expect(mockedFetch.mock.calls.length).toBe(2);
expect(retryFn.mock.calls.length).toBe(2);
Expand Down