Add retry count to `afterResponse` and `beforeError` hooks (#763)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by GitHub · parent 5fc5bfb · Browse files · 5 files·+163 added−11 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+163 added−11 removed
- tests:+79 added−0 removed
- other:+84 added−11 removed
Provenance
- Commit
37fc250- Tree
ab0749c- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
5fc5bfb
5 files changed+163 added−11 removed
modified:source/core/Ky.ts+2 added-1 removed
45 unmodified lines46 const modifiedResponse = await hook(47 ky.request,48 ky.#getNormalizedOptions(),49 ky._decorateResponse(response.clone()),50+ {retryCount: ky._retryCount},51 );52 53 if (modifiedResponse instanceof globalThis.Response) {54 response = modifiedResponse;6 unmodified lines61 let error = new HTTPError(response, ky.request, ky.#getNormalizedOptions());62 63 for (const hook of ky._options.hooks.beforeError) {64 // eslint-disable-next-line no-await-in-loop64- error = await hook(error);65+ error = await hook(error, {retryCount: ky._retryCount});66 }67 68 throw error;69 }311 unmodified linesmodified:source/types/hooks.ts+53 added-7 removed
12345678910111213145 unmodified lines20212223242526272829303132333435363738394041424326444546472948495051525354555657585960616251 unmodified lines114115116117901181191201211222 unmodified lines12512612712810112913013113213313413513613711013813914014114214314414511814614714814915015115215315415515615715815916016116216316416512916616716816917011 unmodified lines1821831841851861871881891901911921931941951961971984 unmodified linesimport {type stop} from '../core/constants.js';import type {KyRequest, KyResponse, HTTPError} from '../index.js';import type {NormalizedOptions} from './options.js';
export type BeforeRequestState = { /** The number of retries attempted. `0` for the initial request, increments with each retry.
This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., avoiding overwriting headers set in `beforeRetry`). */ retryCount: number;};
export type BeforeRequestHook = (5 unmodified linesexport type BeforeRetryState = { request: KyRequest; options: NormalizedOptions; error: Error;
/** The number of retries attempted. Always `>= 1` since this hook is only called during retries, not on the initial request. */ retryCount: number;};export type BeforeRetryHook = (options: BeforeRetryState) => typeof stop | void | Promise<typeof stop | void>;
export type AfterResponseState = { /** The number of retries attempted. `0` for the initial request, increments with each retry.
This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., showing a notification only on the final retry). */ retryCount: number;};
export type AfterResponseHook = ( request: KyRequest, options: NormalizedOptions, response: KyResponse response: KyResponse, state: AfterResponseState) => Response | void | Promise<Response | void>;
export type BeforeErrorHook = (error: HTTPError) => HTTPError | Promise<HTTPError>;export type BeforeErrorState = { /** The number of retries attempted. `0` for the initial request, increments with each retry.
This allows you to distinguish between the initial request and retries, which is useful when you need different error handling based on retry attempts (e.g., showing different error messages on the final attempt). */ retryCount: number;};
export type BeforeErrorHook = (error: HTTPError, state: BeforeErrorState) => HTTPError | Promise<HTTPError>;
export type Hooks = { /** This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives the normalized request, options, and a state object. You could, for example, modify `request.headers` here.
51 unmodified lines */ beforeRetry?: BeforeRetryHook[];
/** This hook enables you to read and optionally modify the response. The hook function receives normalized input, options, and a clone of the response as arguments. The return value of the hook function will be used by Ky as the response object if it's an instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response). This hook enables you to read and optionally modify the response. The hook function receives normalized request, options, a clone of the response, and a state object. The return value of the hook function will be used by Ky as the response object if it's an instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
@default []
@example2 unmodified lines
const response = await ky('https://example.com', { hooks: { afterResponse: [ (_input, _options, response) => { (_request, _options, response) => { // You could do something with the response, for example, logging. log(response);
// Or return a `Response` instance to overwrite the response. return new Response('A different response', {status: 200}); },
// Or retry with a fresh token on a 403 error async (input, options, response) => { async (request, options, response) => { if (response.status === 403) { // Get a fresh token const token = await ky('https://example.com/token').text();
// Retry with the token options.headers.set('Authorization', `token ${token}`);
return ky(input, options); return ky(request, options); } },
// Or show a notification only on the last retry for 5xx errors (request, options, response, {retryCount}) => { if (response.status >= 500 && response.status <= 599) { if (retryCount === options.retry.limit) { showNotification('Request failed after all retries'); } } } ] } }); ``` */ afterResponse?: AfterResponseHook[];
/** This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives a `HTTPError` as an argument and should return an instance of `HTTPError`. This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives a `HTTPError` and a state object as arguments and should return an instance of `HTTPError`.
@default []
@example11 unmodified lines error.message = `${body.message} (${response.status})`; }
return error; },
// Or show different message based on retry count (error, {retryCount}) => { if (retryCount === error.options.retry.limit) { error.message = `${error.message} (failed after ${retryCount} retries)`; }
return error; } ] } });4 unmodified linesmodified:source/index.ts+2 added
50 unmodified lines51 BeforeRequestState,52 BeforeRetryHook,53 BeforeRetryState,54 BeforeErrorHook,55+ BeforeErrorState,56 AfterResponseHook,57+ AfterResponseState,58 } from './types/hooks.js';59 60 export type {ResponsePromise} from './types/ResponsePromise.js';61 export type {KyRequest} from './types/request.js';4 unmodified linesmodified:test/hooks.ts+79 added
749 unmodified lines750 });751 752 await server.close();753 });754+755+test('afterResponse hook receives retryCount in state parameter', async t => {756+ let requestCount = 0;757+ const retryCounts: number[] = [];758+759+ const server = await createHttpTestServer();760+ server.get('/', (_request, response) => {761+ requestCount++;762+763+ if (requestCount <= 2) {764+ // First two requests fail765+ response.sendStatus(500);766+ } else {767+ // Third request succeeds768+ response.end('success');769+ }770+ });771+772+ await ky.get(server.url, {773+ retry: {774+ limit: 2,775+ },776+ hooks: {777+ afterResponse: [778+ (_request, _options, _response, state) => {779+ t.is(typeof state.retryCount, 'number');780+ retryCounts.push(state.retryCount);781+ },782+ ],783+ },784+ });785+786+ // AfterResponse should be called 3 times (initial + 2 retries)787+ t.is(requestCount, 3);788+ t.deepEqual(retryCounts, [0, 1, 2]);789+790+ await server.close();791+});792+793+test('beforeError hook receives retryCount in state parameter', async t => {794+ let requestCount = 0;795+ let errorRetryCount: number | undefined;796+797+ const server = await createHttpTestServer();798+ server.get('/', (_request, response) => {799+ requestCount++;800+ // All requests fail801+ response.sendStatus(500);802+ });803+804+ try {805+ await ky.get(server.url, {806+ retry: {807+ limit: 2,808+ },809+ hooks: {810+ beforeError: [811+ (error: HTTPError, state) => {812+ // Verify retryCount exists in state and is a number813+ t.is(typeof state.retryCount, 'number');814+ t.true(state.retryCount >= 0);815+ errorRetryCount = state.retryCount;816+ return error;817+ },818+ ],819+ },820+ });821+ t.fail('Should have thrown an error');822+ } catch (error: any) {823+ t.true(error instanceof HTTPError);824+ // State should have had retryCount = 2 (after 2 retries)825+ t.is(errorRetryCount, 2);826+ }827+828+ // Should have made 3 requests total (initial + 2 retries)829+ t.is(requestCount, 3);830+831+ await server.close();832+});modified:readme.md+27 added-3 removed
286 unmodified lines287 Default: `[]`288 289 This hook enables you to modify the request right before retry. Ky will make no further changes to the request after this. The hook function receives an object with the normalized request and options, an error instance, and the retry count. You could, for example, modify `request.headers` here.290 291+The `retryCount` is always `>= 1` since this hook is only called during retries, not on the initial request.292+293 If the request received a response, the error will be of type `HTTPError` and the `Response` object will be available at `error.response`. Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will not be an instance of `HTTPError`.294 295 You can prevent Ky from retrying the request by throwing an error. Ky will not handle it in any way and the error will be propagated to the request initiator. The rest of the `beforeRetry` hooks will not be called in this case. Alternatively, you can return the [`ky.stop`](#kystop) symbol to do the same thing but without propagating an error (this has some limitations, see `ky.stop` docs for details).296 16 unmodified lines313 314 Type: `Function[]`\315 Default: `[]`316 315-This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives a `HTTPError` as an argument and should return an instance of `HTTPError`.317+This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives a `HTTPError` and a state object as arguments and should return an instance of `HTTPError`.318 319+The `state.retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between the initial request and retries, which is useful when you need different error handling based on retry attempts (e.g., showing different error messages on the final attempt).320+321 ```js322 import ky from 'ky';323 324 await ky('https://example.com', {7 unmodified lines332 error.message = `${body.message} (${response.status})`;333 }334 335 return error;336+ },337+338+ // Or show different message based on retry count339+ (error, state) => {340+ if (state.retryCount === error.options.retry.limit) {341+ error.message = `${error.message} (failed after ${state.retryCount} retries)`;342+ }343+344+ return error;345 }346 ]347 }348 });3 unmodified lines352 353 Type: `Function[]`\354 Default: `[]`355 343-This hook enables you to read and optionally modify the response. The hook function receives normalized request, options, and a clone of the response as arguments. The return value of the hook function will be used by Ky as the response object if it's an instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).356+This hook enables you to read and optionally modify the response. The hook function receives normalized request, options, a clone of the response, and a state object. The return value of the hook function will be used by Ky as the response object if it's an instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).357 358+The `state.retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., showing a notification only on the final retry).359+360 ```js361 import ky from 'ky';362 363 const response = await ky('https://example.com', {15 unmodified lines379 380 // Retry with the token381 request.headers.set('Authorization', `token ${token}`);382 368- return ky(request);383+ return ky(request, options);384 }385+ },386+387+ // Or show a notification only on the last retry for 5xx errors388+ (request, options, response, {retryCount}) => {389+ if (response.status >= 500 && response.status <= 599) {390+ if (retryCount === options.retry.limit) {391+ showNotification('Request failed after all retries');392+ }393+ }394 }395 ]396 }397 });441 unmodified lines