Allow `beforeRetry` hooks to return a `Request` or `Response` (#774)
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 caf78d2 · Browse files · 4 files·+215 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+215 added−3 removed
- tests:+109 added−0 removed
- other:+106 added−3 removed
Provenance
- Commit
a51bb1e- Tree
c23b6c7- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
caf78d2
4 files changed+215 added−3 removed
modified:source/core/Ky.ts+12 added-1 removed
353 unmodified lines354 355 return response;356 }357 358- async #retry<T extends (...arguments_: any) => Promise<any>>(function_: T): Promise<ReturnType<T> | void> {358+ async #retry<T extends (...arguments_: any) => Promise<any>>(function_: T): Promise<ReturnType<T> | Response | void> {359 try {360 return await function_();361 } catch (error) {362 const ms = Math.min(await this.#calculateRetryDelay(error), maxSafeTimeout);12 unmodified lines375 error: error as Error,376 retryCount: this.#retryCount,377 });378 379+ // If a Request is returned, use it for the retry380+ if (hookResult instanceof globalThis.Request) {381+ this.request = hookResult;382+ break;383+ }384+385+ // If a Response is returned, use it and skip the retry386+ if (hookResult instanceof globalThis.Response) {387+ return hookResult;388+ }389+390 // If `stop` is returned from the hook, the retry process is stopped391 if (hookResult === stop) {392 return;393 }55 unmodified linesmodified:source/types/hooks.ts+49 added-2 removed
25 unmodified lines26 The number of retries attempted. Always `>= 1` since this hook is only called during retries, not on the initial request.27 */28 retryCount: number;29 };30-export type BeforeRetryHook = (options: BeforeRetryState) => typeof stop | void | Promise<typeof stop | void>;30+export type BeforeRetryHook = (options: BeforeRetryState) => Request | Response | typeof stop | void | Promise<Request | Response | typeof stop | void>;31 32 export type AfterResponseState = {33 /**34 The number of retries attempted. `0` for the initial request, increments with each retry.54 unmodified lines89 90 /**91 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.92 93+ The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing retry request, or return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to skip the retry and use that response instead. **Note:** Returning a request or response skips remaining `beforeRetry` hooks.94+95 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`.96 97 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`](#ky.stop) symbol to do the same thing but without propagating an error (this has some limitations, see `ky.stop` docs for details).98 99+ **Modifying headers:**100+101 @example102 ```103 import ky from 'ky';104 1 unmodified line106 hooks: {107 beforeRetry: [108 async ({request, options, error, retryCount}) => {109 const token = await ky('https://example.com/refresh-token');106- options.headers.set('Authorization', `token ${token}`);110+ request.headers.set('Authorization', `token ${token}`);111 }112 ]113 }114 });115 ```116 117+ **Modifying the request URL:**118+119+ @example120+ ```121+ import ky from 'ky';122+123+ const response = await ky('https://example.com/api', {124+ hooks: {125+ beforeRetry: [126+ async ({request, error}) => {127+ // Add query parameters based on error response128+ if (error.response) {129+ const body = await error.response.json();130+ const url = new URL(request.url);131+ url.searchParams.set('processId', body.processId);132+ return new Request(url, request);133+ }134+ }135+ ]136+ }137+ });138+ ```139+140+ **Returning a cached response:**141+142+ @example143+ ```144+ import ky from 'ky';145+146+ const response = await ky('https://example.com/api', {147+ hooks: {148+ beforeRetry: [149+ ({error, retryCount}) => {150+ // Use cached response instead of retrying151+ if (retryCount > 1 && cachedResponse) {152+ return cachedResponse;153+ }154+ }155+ ]156+ }157+ });158+ ```159+160 @default []161 */162 beforeRetry?: BeforeRetryHook[];163 86 unmodified linesmodified:test/hooks.ts+109 added
828 unmodified lines829 t.is(requestCount, 3);830 831 await server.close();832 });833+834+test('beforeRetry hook can return modified Request with new URL', async t => {835+ let requestCount = 0;836+837+ const server = await createHttpTestServer();838+ server.get('/', (request, response) => {839+ requestCount++;840+841+ // Check if the required query parameter is present842+ const url = new URL(request.url, `http://${request.headers.host}`);843+ const processId = url.searchParams.get('processId');844+845+ if (processId === '2222') {846+ response.end('success');847+ } else {848+ response.sendStatus(500);849+ }850+ });851+852+ const result = await ky.get(server.url, {853+ retry: {854+ limit: 1,855+ },856+ hooks: {857+ beforeRetry: [858+ ({request}) => {859+ // Return a new Request with the required query parameter860+ const url = new URL(request.url);861+ url.searchParams.set('processId', '2222');862+ return new Request(url, request);863+ },864+ ],865+ },866+ }).text();867+868+ t.is(result, 'success');869+ t.is(requestCount, 2); // Initial request + 1 retry870+871+ await server.close();872+});873+874+test('beforeRetry hook can return Response to skip retry', async t => {875+ let requestCount = 0;876+877+ const server = await createHttpTestServer();878+ server.get('/', (_request, response) => {879+ requestCount++;880+ response.sendStatus(500);881+ });882+883+ const result = await ky.get(server.url, {884+ retry: {885+ limit: 3,886+ },887+ hooks: {888+ beforeRetry: [889+ () => new Response('fallback', {status: 200}),890+ ],891+ },892+ }).text();893+894+ t.is(result, 'fallback');895+ t.is(requestCount, 1); // Only initial request, no retry896+897+ await server.close();898+});899+900+test('beforeRetry hook returning Request/Response stops processing remaining hooks', async t => {901+ let requestCount = 0;902+ let firstHookCalled = false;903+ let secondHookCalled = false;904+905+ const server = await createHttpTestServer();906+ server.get('/', (request, response) => {907+ requestCount++;908+909+ if (request.headers['x-first-hook']) {910+ response.end('success');911+ } else {912+ response.sendStatus(500);913+ }914+ });915+916+ const result = await ky.get(server.url, {917+ retry: {918+ limit: 1,919+ },920+ hooks: {921+ beforeRetry: [922+ ({request}) => {923+ firstHookCalled = true;924+ const newRequest = new Request(request.url, request);925+ newRequest.headers.set('x-first-hook', 'true');926+ return newRequest;927+ },928+ () => {929+ secondHookCalled = true;930+ },931+ ],932+ },933+ }).text();934+935+ t.is(result, 'success');936+ t.true(firstHookCalled);937+ t.false(secondHookCalled);938+ t.is(requestCount, 2); // Initial request + 1 retry939+940+ await server.close();941+});modified:readme.md+45 added
375 unmodified lines376 Default: `[]`377 378 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.379 380+The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing retry request, or return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to skip the retry and use that response instead. **Note:** Returning a request or response skips remaining `beforeRetry` hooks.381+382 The `retryCount` is always `>= 1` since this hook is only called during retries, not on the initial request.383 384 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`.385 386 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).387 388+**Modifying headers:**389+390 ```js391 import ky from 'ky';392 393 const response = await ky('https://example.com', {7 unmodified lines401 }402 });403 ```404 405+**Modifying the request URL:**406+407+```js408+import ky from 'ky';409+410+const response = await ky('https://example.com/api', {411+ hooks: {412+ beforeRetry: [413+ async ({request, error}) => {414+ // Add query parameters based on error response415+ if (error.response) {416+ const body = await error.response.json();417+ const url = new URL(request.url);418+ url.searchParams.set('processId', body.processId);419+ return new Request(url, request);420+ }421+ }422+ ]423+ }424+});425+```426+427+**Returning a cached response:**428+429+```js430+import ky from 'ky';431+432+const response = await ky('https://example.com/api', {433+ hooks: {434+ beforeRetry: [435+ ({error, retryCount}) => {436+ // Use cached response instead of retrying437+ if (retryCount > 1 && cachedResponse) {438+ return cachedResponse;439+ }440+ }441+ ]442+ }443+});444+```445+446 ###### hooks.beforeError447 448 Type: `Function[]`\449 Default: `[]`707 unmodified lines