Skip to content
Myr

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

4 files+215 added−3 removed

modified:source/core/Ky.ts+12 added-1 removed
353 unmodified lines
354355 return response;356 }357358 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 lines
375 error: error as Error,376 retryCount: this.#retryCount,377 });378379 // If a Request is returned, use it for the retry380 if (hookResult instanceof globalThis.Request) {381 this.request = hookResult;382 break;383 }384385 // If a Response is returned, use it and skip the retry386 if (hookResult instanceof globalThis.Response) {387 return hookResult;388 }389390 // If `stop` is returned from the hook, the retry process is stopped391 if (hookResult === stop) {392 return;393 }
55 unmodified lines
modified:source/types/hooks.ts+49 added-2 removed
25 unmodified lines
26 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};30export type BeforeRetryHook = (options: BeforeRetryState) => typeof stop | void | Promise<typeof stop | void>;30export type BeforeRetryHook = (options: BeforeRetryState) => Request | Response | typeof stop | void | Promise<Request | Response | typeof stop | void>;3132export type AfterResponseState = {33 /**34 The number of retries attempted. `0` for the initial request, increments with each retry.
54 unmodified lines
8990 /**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.9293 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.9495 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`.9697 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).9899 **Modifying headers:**100101 @example102 ```103 import ky from 'ky';104
1 unmodified line
106 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 ```116117 **Modifying the request URL:**118119 @example120 ```121 import ky from 'ky';122123 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 ```139140 **Returning a cached response:**141142 @example143 ```144 import ky from 'ky';145146 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 ```159160 @default []161 */162 beforeRetry?: BeforeRetryHook[];163
86 unmodified lines
modified:test/hooks.ts+109 added
828 unmodified lines
829 t.is(requestCount, 3);830831 await server.close();832});833834test('beforeRetry hook can return modified Request with new URL', async t => {835 let requestCount = 0;836837 const server = await createHttpTestServer();838 server.get('/', (request, response) => {839 requestCount++;840841 // 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');844845 if (processId === '2222') {846 response.end('success');847 } else {848 response.sendStatus(500);849 }850 });851852 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();867868 t.is(result, 'success');869 t.is(requestCount, 2); // Initial request + 1 retry870871 await server.close();872});873874test('beforeRetry hook can return Response to skip retry', async t => {875 let requestCount = 0;876877 const server = await createHttpTestServer();878 server.get('/', (_request, response) => {879 requestCount++;880 response.sendStatus(500);881 });882883 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();893894 t.is(result, 'fallback');895 t.is(requestCount, 1); // Only initial request, no retry896897 await server.close();898});899900test('beforeRetry hook returning Request/Response stops processing remaining hooks', async t => {901 let requestCount = 0;902 let firstHookCalled = false;903 let secondHookCalled = false;904905 const server = await createHttpTestServer();906 server.get('/', (request, response) => {907 requestCount++;908909 if (request.headers['x-first-hook']) {910 response.end('success');911 } else {912 response.sendStatus(500);913 }914 });915916 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();934935 t.is(result, 'success');936 t.true(firstHookCalled);937 t.false(secondHookCalled);938 t.is(requestCount, 2); // Initial request + 1 retry939940 await server.close();941});
modified:readme.md+45 added
375 unmodified lines
376Default: `[]`377378This 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.379380The 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.381382The `retryCount` is always `>= 1` since this hook is only called during retries, not on the initial request.383384If 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`.385386You 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).387388**Modifying headers:**389390```js391import ky from 'ky';392393const response = await ky('https://example.com', {
7 unmodified lines
401 }402});403```404405**Modifying the request URL:**406407```js408import ky from 'ky';409410const 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```426427**Returning a cached response:**428429```js430import ky from 'ky';431432const 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```445446###### hooks.beforeError447448Type: `Function[]`\449Default: `[]`
707 unmodified lines