Skip to content
Myr

Unify hook signatures around a single state object (#827)

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 dfa3f59 · Browse files · 13 files+146 added−138 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

13 files+146 added−138 removed

  • tests:+75 added−75 removed
  • other:+71 added−63 removed

13 files+146 added−138 removed

modified:source/core/constants.ts+1 added-1 removed
165 unmodified lines
166167const api = ky.extend({168 hooks: {169 afterResponse: [170 async (request, options, response) => {170 async ({request, response}) => {171 // Retry based on response body content172 if (response.status === 200) {173 const data = await response.clone().json();174
110 unmodified lines
modified:source/core/Ky.ts+15 added-12 removed
64 unmodified lines
6566 let modifiedResponse;67 try {68 // eslint-disable-next-line no-await-in-loop69 modifiedResponse = await hook(70 ky.request,71 ky.#getNormalizedOptions(),72 clonedResponse,73 {retryCount: ky.#retryCount},74 );69 modifiedResponse = await hook({70 request: ky.request,71 options: ky.#getNormalizedOptions(),72 response: clonedResponse,73 retryCount: ky.#retryCount,74 });75 } catch (error) {76 // Cancel both responses to prevent memory leaks when hook throws77 ky.#cancelResponseBody(clonedResponse);78 ky.#cancelResponseBody(response);
35 unmodified lines
114 error.data = await ky.#getResponseData(response);115116 for (const hook of ky.#options.hooks.beforeError) {117 // eslint-disable-next-line no-await-in-loop118 error = await hook(error, {retryCount: ky.#retryCount});118 error = await hook({119 error,120 retryCount: ky.#retryCount,121 });122 }123124 throw error;125 }
465 unmodified lines
591 }592593 for (const hook of this.#options.hooks.beforeRequest) {594 // eslint-disable-next-line no-await-in-loop592 const result = await hook(593 this.request,594 this.#getNormalizedOptions(),595 {retryCount: this.#retryCount},596 );595 const result = await hook({596 request: this.request,597 options: this.#getNormalizedOptions(),598 retryCount: this.#retryCount,599 });600601 if (result instanceof Response) {602 return result;603 }
42 unmodified lines
modified:source/types/hooks.ts+31 added-26 removed
1 unmodified line
2import type {KyRequest, KyResponse, HTTPError} from '../index.js';3import type {NormalizedOptions} from './options.js';45export type BeforeRequestState = {6 request: KyRequest;7 options: NormalizedOptions;89 /**10 The number of retries attempted. `0` for the initial request, increments with each retry.1112 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`).13 */14 retryCount: number;15};1614export type BeforeRequestHook = (15 request: KyRequest,16 options: NormalizedOptions,17 state: BeforeRequestState18) => Request | Response | void | Promise<Request | Response | void>;17export type BeforeRequestHook = (state: BeforeRequestState) => Request | Response | void | Promise<Request | Response | void>;1819export type BeforeRetryState = {20 request: KyRequest;21 options: NormalizedOptions;
3 unmodified lines
25 The number of retries attempted. Always `>= 1` since this hook is only called during retries, not on the initial request.26 */27 retryCount: number;28};30export type BeforeRetryHook = (options: BeforeRetryState) => Request | Response | typeof stop | void | Promise<Request | Response | typeof stop | void>;2930export type BeforeRetryHook = (state: BeforeRetryState) => Request | Response | typeof stop | void | Promise<Request | Response | typeof stop | void>;3132export type AfterResponseState = {33 request: KyRequest;34 options: NormalizedOptions;35 response: KyResponse;3637 /**38 The number of retries attempted. `0` for the initial request, increments with each retry.3940 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).41 */42 retryCount: number;43};4441export type AfterResponseHook = (42 request: KyRequest,43 options: NormalizedOptions,44 response: KyResponse,45 state: AfterResponseState46) => Response | RetryMarker | void | Promise<Response | RetryMarker | void>;45export type AfterResponseHook = (state: AfterResponseState) => Response | RetryMarker | void | Promise<Response | RetryMarker | void>;4647export type BeforeErrorState = {48 error: HTTPError;4950 /**51 The number of retries attempted. `0` for the initial request, increments with each retry.5253 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).54 */55 retryCount: number;56};5757export type BeforeErrorHook = (error: HTTPError, state: BeforeErrorState) => HTTPError | Promise<HTTPError>;58export type BeforeErrorHook = (state: BeforeErrorState) => HTTPError | Promise<HTTPError>;5960export type Hooks = {61 /**61 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.62 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 a state object with the normalized request, options, and retry count. You could, for example, modify `request.headers` here.6363 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., avoiding overwriting headers set in `beforeRetry`).64 The `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., avoiding overwriting headers set in `beforeRetry`).6566 A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) can be returned from this hook to completely avoid making an HTTP request. This can be used to mock a request, check an internal cache, etc. An **important** consideration when returning a `Response` from this hook is that all the following hooks will be skipped, so **ensure you only return a `Response` from the last hook**.6768 @example
2 unmodified lines
7172 const response = await ky('https://example.com', {73 hooks: {74 beforeRequest: [74 (request, options, {retryCount}) => {75 ({request, retryCount}) => {76 // Only set default auth header on initial request, not on retries77 // (retries may have refreshed token set by beforeRetry)78 if (retryCount === 0) {79 request.headers.set('Authorization', 'token initial-token');
8 unmodified lines
88 */89 beforeRequest?: BeforeRequestHook[];9091 /**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 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 a state object with the normalized request, options, an error instance, and the retry count. You could, for example, modify `request.headers` here.9394 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.9596 If the request received a response, the error will be of type `HTTPError`. The `Response` object will be available at `error.response`, and the pre-parsed response body will be available at `error.data`. 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`.
69 unmodified lines
166 */167 beforeRetry?: BeforeRetryHook[];168169 /**169 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).170 This hook enables you to read and optionally modify the response. The hook function receives a state object with the normalized request, options, a clone of the response, and retry count. 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).171172 The `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).173174 You can also force a retry by returning `ky.retry()` or `ky.retry(options)`. This is useful when you need to retry based on the response body content, even if the response has a successful status code. The retry will respect the retry limit and be observable in `beforeRetry` hooks.175176 @default []177
3 unmodified lines
181182 const response = await ky('https://example.com', {183 hooks: {184 afterResponse: [182 (_request, _options, response) => {185 ({response}) => {186 // You could do something with the response, for example, logging.187 log(response);188189 // Or return a `Response` instance to overwrite the response.190 return new Response('A different response', {status: 200});191 },192193 // Or retry with a fresh token on a 401 error191 async (request, _options, response, state) => {192 if (response.status === 401 && state.retryCount === 0) {194 async ({request, response, retryCount}) => {195 if (response.status === 401 && retryCount === 0) {196 // Only refresh on first 401, not on subsequent retries197 const {token} = await ky.post('https://example.com/auth/refresh').json();198199 const headers = new Headers(request.headers);
6 unmodified lines
206 }207 },208209 // Or force retry based on response body content207 async (request, options, response) => {210 async ({response}) => {211 if (response.status === 200) {212 const data = await response.clone().json();213 if (data.error?.code === 'RATE_LIMIT') {214 // Force retry with custom delay from API response
5 unmodified lines
220 }221 },222223 // Or show a notification only on the last retry for 5xx errors221 (request, options, response, {retryCount}) => {224 ({options, response, retryCount}) => {225 if (response.status >= 500 && response.status <= 599) {226 if (retryCount === options.retry.limit) {227 showNotification('Request failed after all retries');228 }
6 unmodified lines
235 */236 afterResponse?: AfterResponseHook[];237238 /**236 This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives an `HTTPError` and a state object as arguments and should return an instance of `HTTPError`.239 This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives a state object with an `HTTPError` and retry count, and should return an instance of `HTTPError`.240241 The `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).242243 @default []244245 @example246 ```
1 unmodified line
248249 await ky('https://example.com', {250 hooks: {251 beforeError: [247 error => {252 ({error}) => {253 if (254 typeof error.data === 'object'255 && error.data !== null256 && 'message' in error.data
5 unmodified lines
262 return error;263 },264265 // Or show different message based on retry count261 (error, {retryCount}) => {266 ({error, retryCount}) => {267 if (retryCount === error.options.retry.limit) {268 error.message = `${error.message} (failed after ${retryCount} retries)`;269 }270
9 unmodified lines
modified:source/types/ky.ts+1 added-1 removed
modified:source/types/options.ts+1 added-1 removed
256 unmodified lines
257 // Pass data to hooks258 const api = ky.create({259 hooks: {260 beforeRequest: [261 (request, options) => {261 ({request, options}) => {262 const {token} = options.context;263 if (token) {264 request.headers.set('Authorization', `Bearer ${token}`);265 }
121 unmodified lines
modified:test/context.ts+8 added-8 removed
22 unmodified lines
23 context,24 retry: {limit: 0},25 hooks: {26 beforeRequest: [27 (_request, options) => {27 ({options}) => {28 t.deepEqual(options.context, context);29 },30 ],31 afterResponse: [32 async (_input, options, _response) => {32 async ({options}) => {33 t.deepEqual(options.context, context);34 },35 ],36 beforeError: [37 error => {37 ({error}) => {38 t.deepEqual(error.options.context, context);39 return error;40 },41 ],
28 unmodified lines
7071 await baseApi.get('', {72 hooks: {73 beforeRequest: [74 (_request, options) => {74 ({options}) => {75 t.deepEqual(options.context, {base: 'value'});76 },77 ],78 },
3 unmodified lines
82 await extendedApi.get('', {83 context: {request: 'value'},84 hooks: {85 beforeRequest: [86 (_request, options) => {86 ({options}) => {87 t.deepEqual(options.context, {base: 'value', extended: 'value', request: 'value'});88 },89 ],90 },
19 unmodified lines
110 context,111 retry: {limit: 2},112 hooks: {113 beforeRequest: [114 (_request, options) => {114 ({options}) => {115 t.deepEqual(options.context, context);116 callCount++;117 },118 ],
10 unmodified lines
129 });130131 await ky.get(server.url, {132 hooks: {133 beforeRequest: [(_request, options) => t.deepEqual(options.context, {})],133 beforeRequest: [({options}) => t.deepEqual(options.context, {})],134 },135 }).json();136});137
21 unmodified lines
159160 await extendedApi.get('', {161 hooks: {162 beforeRequest: [163 (_request, options) => {163 ({options}) => {164 const context = options.context as any;165 t.is(context.auth.apiKey, 'extended');166 t.is(context.auth.userId, undefined);167 t.is(context.settings.timeout, undefined);
7 unmodified lines
modified:test/formdata-searchparams.ts+1 added-1 removed
95 unmodified lines
96 const result = await ky.post(server.url, {97 body: formData,98 hooks: {99 afterResponse: [100 async (request, options, response) => {100 async ({request, options, response}) => {101 if (response.status === 401) {102 return ky(request, options);103 }104 },
7 unmodified lines
modified:test/hooks.ts+56 added-56 removed
40 unmodified lines
41 .post(server.url, {42 json,43 hooks: {44 beforeRequest: [45 async (request, options) => {45 async ({request, options}) => {46 await delay(100);47 const bodyJson = JSON.parse(options.body as string);48 bodyJson.foo = false;49 return new Request(request, {body: JSON.stringify(bodyJson)});
33 unmodified lines
83 .post(server.url, {84 json,85 hooks: {86 beforeRequest: [87 (request, options) => {87 ({request, options}) => {88 const bodyJson = JSON.parse(options.body as string);89 bodyJson.foo = false;90 return new Request(request, {body: JSON.stringify(bodyJson)});91 },
20 unmodified lines
112 .post(server.url, {113 json,114 hooks: {115 afterResponse: [116 async (_input, _options, response) => {116 async ({response}) => {117 t.is(response.status, 200);118 t.deepEqual(await response.json(), json);119 },120 ],
13 unmodified lines
134135 await ky.get(server.url, {136 hooks: {137 afterResponse: [138 async (_request, _options, response) => {138 async ({response}) => {139 if (response.body) {140 const originalCancel = response.body.cancel.bind(response.body);141 response.body.cancel = async () => {142 didCancelClonedResponseBody = true;
21 unmodified lines
164 const responseText = await ky('https://example.com', {165 fetch: customFetch,166 hooks: {167 afterResponse: [168 (_request, _options, response) => {168 ({response}) => {169 clonedResponse = response;170 return new Response('replacement');171 },172 ],
17 unmodified lines
190 const responseText = await ky('https://example.com', {191 fetch: customFetch,192 hooks: {193 afterResponse: [194 (_request, _options, response) => response,194 ({response}) => response,195 ],196 },197 }).text();198
14 unmodified lines
213 const responseText = await ky('https://example.com', {214 fetch: customFetch,215 hooks: {216 afterResponse: [217 (_request, _options, response) => {217 ({response}) => {218 clones.push(response);219 // Return nothing - clone should be cancelled220 },221 (_request, _options, response) => {221 ({response}) => {222 clones.push(response);223 // Return nothing - clone should be cancelled224 },225 (_request, _options, response) => {225 ({response}) => {226 clones.push(response);227 // Return nothing - clone should be cancelled228 },229 ],
25 unmodified lines
255 ky('https://example.com', {256 fetch: customFetch,257 hooks: {258 afterResponse: [259 (_request, _options, response) => {259 ({response}) => {260 clonedResponse = response;261 throw expectError;262 },263 ],
21 unmodified lines
285 .post(server.url, {286 json,287 hooks: {288 afterResponse: [289 async (_input, _options, response) => {289 async ({response}) => {290 t.is(response.status, 500);291 t.deepEqual(await response.json(), json);292 },293 ],
22 unmodified lines
316 () =>317 new Response(modifiedBody1, {318 status: modifiedStatus1,319 }),320 async (_input, _options, response) => {320 async ({response}) => {321 t.is(response.status, modifiedStatus1);322 t.is(await response.text(), modifiedBody1);323324 return new Response(modifiedBody2, {
64 unmodified lines
389 await ky390 .get(server.url, {391 hooks: {392 afterResponse: [393 (_input, _options, response) => {393 ({response}) => {394 called = true;395 return response;396 },397 ],
25 unmodified lines
423 .post(server.url, {424 json,425 hooks: {426 afterResponse: [427 async (request, options, response) => {427 async ({request, options, response}) => {428 if (response.status === 403) {429 // Retry request with valid token430 return ky(request, {431 ...options,
32 unmodified lines
464 return {awesome: true};465 },466 hooks: {467 afterResponse: [468 async (_request, _options, response) => {468 async ({response}) => {469 t.true(response instanceof Response);470 t.deepEqual(await response.json(), {awesome: true});471 },472 ],
365 unmodified lines
838 await t.throwsAsync(839 ky.post(server.url, {840 hooks: {841 beforeError: [842 (error: HTTPError) => {842 ({error}) => {843 const {response} = error;844845 if (response?.body) {846 error.name = 'GitHubError';
22 unmodified lines
869 await t.throwsAsync(870 ky.post(server.url, {871 hooks: {872 beforeError: [873 async (error: HTTPError) => {873 async ({error}) => {874 const body = error.data as {reason: string};875876 error.name = 'GitHubError';877 error.message = `${body.reason} --- (${error.response.status})`.trim();
29 unmodified lines
907908 const result = await ky.get(server.url, {909 hooks: {910 beforeRequest: [911 (request, _options, {retryCount}) => {911 ({request, retryCount}) => {912 retryCounts.push(retryCount);913 // Only set default token on initial request914 if (retryCount === 0) {915 request.headers.set('Authorization', 'token initial-token');
24 unmodified lines
940941 await ky.get(server.url, {942 hooks: {943 beforeRequest: [944 (_request, options) => {944 ({options}) => {945 // Verify hooks field is not present946 t.false('hooks' in options);947948 // Verify options object is frozen (can't add/modify properties)
34 unmodified lines
983 limit: 2,984 },985 hooks: {986 afterResponse: [987 (_request, _options, _response, state) => {988 t.is(typeof state.retryCount, 'number');989 retryCounts.push(state.retryCount);987 ({retryCount}) => {988 t.is(typeof retryCount, 'number');989 retryCounts.push(retryCount);990 },991 ],992 },993 });
20 unmodified lines
1014 limit: 2,1015 },1016 hooks: {1017 beforeError: [1018 (error: HTTPError, state) => {1018 ({error, retryCount}) => {1019 // Verify retryCount exists in state and is a number1020 t.is(typeof state.retryCount, 'number');1021 t.true(state.retryCount >= 0);1022 errorRetryCount = state.retryCount;1020 t.is(typeof retryCount, 'number');1021 t.true(retryCount >= 0);1022 errorRetryCount = retryCount;1023 return error;1024 },1025 ],1026 },
133 unmodified lines
1160 limit: 2,1161 },1162 hooks: {1163 afterResponse: [1164 async (_request, _options, response) => {1164 async ({response}) => {1165 const data = await response.clone().json();1166 if (data.error?.code === 'RATE_LIMIT') {1167 return ky.retry();1168 }
24 unmodified lines
1193 const result = await ky('https://example.test', {1194 fetch: customFetch,1195 hooks: {1196 afterResponse: [1197 (_request, _options, response) => {1197 ({response}) => {1198 response.clone();1199 if (response.status === 401) {1200 return ky.retry();1201 }
27 unmodified lines
1229 limit: 2,1230 },1231 hooks: {1232 afterResponse: [1233 async (_request, _options, response) => {1233 async ({response}) => {1234 const data = await response.clone().json();1235 if (data.error?.code === 'RATE_LIMIT') {1236 return ky.retry({1237 delay: data.error.retryAfter * 1000,
27 unmodified lines
1265 limit: 2,1266 },1267 hooks: {1268 afterResponse: [1269 async (_request, _options, response) => {1269 async ({response}) => {1270 const data = await response.clone().json();1271 if (data.error?.code === 'RATE_LIMIT') {1272 return ky.retry();1273 }
31 unmodified lines
1305 limit: 2,1306 },1307 hooks: {1308 afterResponse: [1309 async (_request, _options, response) => {1309 async ({response}) => {1310 const data = await response.clone().json();1311 if (data.error?.code === 'RATE_LIMIT') {1312 return ky.retry({code: 'RATE_LIMIT'});1313 }
40 unmodified lines
1354 },1355 },1356 hooks: {1357 afterResponse: [1358 async (_request, _options, response) => {1358 async ({response}) => {1359 const data = await response.clone().json();1360 if (data.error?.code === 'CUSTOM_ERROR') {1361 return ky.retry();1362 }
29 unmodified lines
1392 limit: 2,1393 },1394 hooks: {1395 afterResponse: [1396 async (_request, _options, response) => {1396 async ({response}) => {1397 const data = await response.clone().json();1398 if (data.error?.code === 'RATE_LIMIT') {1399 return ky.retry();1400 }
27 unmodified lines
1428 limit: 2,1429 },1430 hooks: {1431 afterResponse: [1432 async (_request, _options, response) => {1432 async ({response}) => {1433 firstHookCallCount++;1434 const data = await response.clone().json();1435 if (data.error?.code === 'RATE_LIMIT') {1436 return ky.retry();
30 unmodified lines
1467 limit: 2,1468 },1469 hooks: {1470 afterResponse: [1471 async (_request, _options, response) => {1471 async ({response}) => {1472 const data = await response.clone().json();1473 if (data.error?.code === 'RETRY_NOW') {1474 return ky.retry({delay: 0}); // Instant retry, no delay1475 }
23 unmodified lines
14991500 const result = await ky.get(`${server.url}/primary`, {1501 hooks: {1502 afterResponse: [1503 async (request, _options, response) => {1503 async ({request, response}) => {1504 const data = await response.clone().json();1505 if (data.error?.code === 'FALLBACK_TO_BACKUP') {1506 return ky.retry({1507 request: new Request(`${server.url}/backup`, {
30 unmodified lines
1538 const result = await ky.get(server.url, {1539 headers: {'X-Auth-Token': 'original-token'},1540 hooks: {1541 afterResponse: [1542 async (request, _options, response) => {1542 async ({request, response}) => {1543 const data = await response.clone().json();1544 if (data.error?.code === 'TOKEN_REFRESH' && data.error.newToken) {1545 return ky.retry({1546 request: new Request(request, {
34 unmodified lines
15811582 const result = await ky.post(server.url, {1583 hooks: {1584 afterResponse: [1585 async (request, _options, response) => {1585 async ({request, response}) => {1586 const data = await response.clone().json();1587 if (data.error?.code === 'METHOD_OVERLOAD' && request.method === 'POST') {1588 return ky.retry({1589 request: new Request(request, {
30 unmodified lines
16201621 const result = await ky.get(server.url, {1622 hooks: {1623 afterResponse: [1624 async (request, _options, response) => {1624 async ({request, response}) => {1625 const data = await response.clone().json();1626 if (data.error?.code === 'RETRY_WITH_CUSTOM_REQUEST') {1627 return ky.retry({1628 request: new Request(request, {
50 unmodified lines
1679 ky.get(server.url, {1680 retry: {limit: 2},1681 hooks: {1682 afterResponse: [1683 async (request, _options, response) => {1683 async ({request, response}) => {1684 const data = await response.clone().json();1685 if (data.error?.code === 'ALWAYS_RETRY') {1686 // Always force retry with custom request1687 return ky.retry({
26 unmodified lines
17141715 const result = await ky.get(server.url, {1716 hooks: {1717 afterResponse: [1718 async (request, _options, response) => {1718 async ({request, response}) => {1719 const data = await response.clone().json();1720 if (data.error?.code === 'CUSTOM_REQUEST_RETRY') {1721 return ky.retry({1722 request: new Request(request),
39 unmodified lines
17621763 const result = await ky.get(`${server.url}/primary`, {1764 hooks: {1765 afterResponse: [1766 async (request, _options, response) => {1766 async ({request, response}) => {1767 const data = await response.clone().json();1768 if (data.error?.code === 'FALLBACK_WITH_DELAY') {1769 return ky.retry({1770 request: new Request(`${server.url}/backup`, {
33 unmodified lines
1804 const result = await ky.post(server.url, {1805 json: {original: true},1806 hooks: {1807 afterResponse: [1808 async (request, _options, response) => {1808 async ({request, response}) => {1809 const data = await response.clone().json();1810 if (data.error?.code === 'RETRY_WITH_MODIFIED_BODY') {1811 return ky.retry({1812 request: new Request(request.url, {
33 unmodified lines
1846 timeout: 1000, // Timeout configured but shouldn't trigger1847 retry: {limit: 2},1848 hooks: {1849 afterResponse: [1850 async (request, _options, response) => {1850 async ({request, response}) => {1851 const data = await response.clone().json();1852 if (data.error?.code === 'NEED_FALLBACK') {1853 // Custom request should inherit proper timeout signal1854 return ky.retry({
28 unmodified lines
18831884 const result = await ky.get(server.url, {1885 hooks: {1886 afterResponse: [1887 async (request, _options, response) => {1887 async ({request, response}) => {1888 const data = await response.clone().json();1889 if (data.error?.code === 'NEED_CUSTOM_REQUEST') {1890 // Create custom request with aborted signal1891 const abortController = new AbortController();
38 unmodified lines
1930 limit: 2,1931 },1932 hooks: {1933 afterResponse: [1934 async (_request, _options, response) => {1934 async ({response}) => {1935 const data = await response.clone().json();1936 if (data.error?.code === 'NEEDS_VALIDATION') {1937 return ky.retry({1938 code: 'VALIDATION_ERROR',
39 unmodified lines
1978 limit: 2,1979 },1980 hooks: {1981 afterResponse: [1982 async (_request, _options, response) => {1982 async ({response}) => {1983 const data = await response.clone().json();1984 if (data.error?.code === 'NEEDS_VALIDATION') {1985 // JS users (or TS users bypassing types) can pass non-Error values1986 return ky.retry({
41 unmodified lines
2028 limit: 2,2029 },2030 hooks: {2031 afterResponse: [2032 async (_request, _options, response) => {2032 async ({response}) => {2033 if (response.status === 401) {2034 return ky.retry();2035 }2036 },
31 unmodified lines
20682069 const api = ky.extend({2070 hooks: {2071 afterResponse: [2072 async (request, _options, response, state) => {2073 if (response.status === 401 && state.retryCount === 0) {2072 async ({request, response, retryCount}) => {2073 if (response.status === 401 && retryCount === 0) {2074 const {token} = await ky.post(`${server.url}/auth/refresh`).json<{token: string}>();20752076 const headers = new Headers(request.headers);2077 headers.set('Authorization', `Bearer ${token}`);
40 unmodified lines
21182119 const api = ky.extend({2120 hooks: {2121 afterResponse: [2122 async (request, _options, response, state) => {2123 if (response.status === 401 && state.retryCount === 0) {2122 async ({request, response, retryCount}) => {2123 if (response.status === 401 && retryCount === 0) {2124 const {token} = await ky.post(`${server.url}/auth/refresh`).json<{token: string}>();21252126 const headers = new Headers(request.headers);2127 headers.set('Authorization', `Bearer ${token}`);
45 unmodified lines
21732174 const api = ky.extend({2175 hooks: {2176 afterResponse: [2177 async (request, _options, response, state) => {2178 if (response.status === 401 && state.retryCount === 0) {2177 async ({request, response, retryCount}) => {2178 if (response.status === 401 && retryCount === 0) {2179 const {token} = await ky.post(`${server.url}/auth/refresh`).json<{token: string}>();21802181 const headers = new Headers(request.headers);2182 headers.set('Authorization', `Bearer ${token}`);
46 unmodified lines
22292230 const api = ky.extend({2231 hooks: {2232 afterResponse: [2233 async (request, _options, response, state) => {2234 if (response.status === 401 && state.retryCount === 0) {2233 async ({request, response, retryCount}) => {2234 if (response.status === 401 && retryCount === 0) {2235 const {token} = await ky.post(`${server.url}/auth/refresh`).json<{token: string}>();22362237 const headers = new Headers(request.headers);2238 headers.set('Authorization', `Bearer ${token}`);
29 unmodified lines
modified:test/http-error.ts+2 added-2 removed
208 unmodified lines
209 let hookData: unknown;210 await t.throwsAsync(ky.get(server.url, {211 hooks: {212 beforeError: [213 error => {213 ({error}) => {214 hookData = error.data;215 return error;216 },217 ],
268 unmodified lines
486 retry: 0,487 timeout: false,488 hooks: {489 afterResponse: [490 (_request, _options, response) => {490 ({response}) => {491 void response.text();492 return response;493 },494 ],
38 unmodified lines
modified:test/main.ts+2 added-2 removed
536 unmodified lines
537 await ky.get(server.url, {538 throwHttpErrors: false,539 hooks: {540 beforeRequest: [541 (_request, options) => {541 ({options}) => {542 booleanTypeInHook = options.throwHttpErrors;543 },544 ],545 },
7 unmodified lines
553 await ky.get(server.url, {554 throwHttpErrors: throwFunction,555 hooks: {556 beforeRequest: [557 (_request, options) => {557 ({options}) => {558 functionTypeInHook = options.throwHttpErrors;559 },560 ],561 },
483 unmodified lines
modified:test/methods.ts+3 added-3 removed
11 unmodified lines
12 ky(server.url, {13 method: 'get',14 hooks: {15 beforeRequest: [16 (_input, options) => {16 ({options}) => {17 t.is(options.method, 'GET');18 },19 ],20 },
12 unmodified lines
33 await t.notThrowsAsync(34 ky(server.url, {35 hooks: {36 beforeRequest: [37 (_input, options) => {37 ({options}) => {38 t.is(options.method, 'GET');39 },40 ],41 },
14 unmodified lines
56 ky(server.url, {57 method: 'report',58 hooks: {59 beforeRequest: [60 (_input, options) => {60 ({options}) => {61 t.is(options.method, 'report');62 },63 ],64 },
13 unmodified lines
modified:test/stream.ts+3 added-3 removed
138 unmodified lines
139 attemptEvents.push([]);140 },141 ],142 afterResponse: [143 async (request, _normalizedOptions, response) => {143 async ({request, response}) => {144 if (response.status === 500) {145 return ky.retry({request: new Request(request)});146 }147 },
54 unmodified lines
202 methods: ['post'],203 },204 hooks: {205 afterResponse: [206 async (request, _normalizedOptions, response) => {206 async ({request, response}) => {207 if (response.status === 500) {208 return ky.retry({request: new Request(request)});209 }210 },
122 unmodified lines
333 attempts.push([]);334 },335 ],336 afterResponse: [337 async (request, _normalizedOptions, response) => {337 async ({request, response}) => {338 if (response.status === 500) {339 return ky.retry({340 request: new Request(request, {body: updatedPayloadString}),341 });
105 unmodified lines
modified:readme.md+22 added-22 removed
345 unmodified lines
346347Type: `Function[]`\348Default: `[]`349350This 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 the `request.headers` here.350This 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 a state object with the normalized request, options, and retry count. You could, for example, modify the `request.headers` here.351352The `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., avoiding overwriting headers set in `beforeRetry`).352The `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., avoiding overwriting headers set in `beforeRetry`).353354The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing request, or return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to completely avoid making an HTTP request. This can be used to mock a request, check an internal cache, etc. An **important** consideration when returning a request or response from this hook is that any remaining `beforeRequest` hooks will be skipped, so you may want to only return them from the last hook.355356```js
1 unmodified line
358359const api = ky.extend({360 hooks: {361 beforeRequest: [362 (request, options, {retryCount}) => {362 ({request, retryCount}) => {363 // Only set default auth header on initial request, not on retries364 // (retries may have refreshed token set by beforeRetry)365 if (retryCount === 0) {366 request.headers.set('Authorization', 'token initial-token');
10 unmodified lines
377378Type: `Function[]`\379Default: `[]`380381This 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.381This 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 a state object with the normalized request, options, an error instance, and the retry count. You could, for example, modify `request.headers` here.382383The 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.384385The `retryCount` is always `>= 1` since this hook is only called during retries, not on the initial request.
68 unmodified lines
454455Type: `Function[]`\456Default: `[]`457458This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives an `HTTPError` and a state object as arguments and should return an instance of `HTTPError`.458This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives a state object with an `HTTPError` and retry count, and should return an instance of `HTTPError`.459460The `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).460The `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).461462```js463import ky from 'ky';464465await ky('https://example.com', {466 hooks: {467 beforeError: [468 error => {468 ({error}) => {469 if (470 typeof error.data === 'object'471 && error.data !== null472 && 'message' in error.data
5 unmodified lines
478 return error;479 },480481 // Or show different message based on retry count482 (error, state) => {483 if (state.retryCount === error.options.retry.limit) {484 error.message = `${error.message} (failed after ${state.retryCount} retries)`;482 ({error, retryCount}) => {483 if (retryCount === error.options.retry.limit) {484 error.message = `${error.message} (failed after ${retryCount} retries)`;485 }486487 return error;488 }
6 unmodified lines
495496Type: `Function[]`\497Default: `[]`498499This 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).499This hook enables you to read and optionally modify the response. The hook function receives a state object with the normalized request, options, a clone of the response, and retry count. 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).500501You can also force a retry by returning [`ky.retry(options)`](#kyretryoptions). This is useful when you need to retry based on the response body content, even if the response has a successful status code. The retry will respect the `retry.limit` option and be observable in `beforeRetry` hooks.502503The `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).503The `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).504505```js506import ky from 'ky';507508const response = await ky('https://example.com', {509 hooks: {510 afterResponse: [511 (_request, _options, response) => {511 ({response}) => {512 // You could do something with the response, for example, logging.513 log(response);514515 // Or return a `Response` instance to overwrite the response.516 return new Response('A different response', {status: 200});517 },518519 // Or retry with a fresh token on a 401 error520 async (request, _options, response, state) => {521 if (response.status === 401 && state.retryCount === 0) {520 async ({request, response, retryCount}) => {521 if (response.status === 401 && retryCount === 0) {522 // Only refresh on first 401, not on subsequent retries523 const {token} = await ky.post('https://example.com/auth/refresh').json();524525 const headers = new Headers(request.headers);
6 unmodified lines
532 }533 },534535 // Or force retry based on response body content536 async (request, options, response) => {536 async ({response}) => {537 if (response.status === 200) {538 const data = await response.clone().json();539 if (data.error?.code === 'RATE_LIMIT') {540 // Retry with custom delay from API response
5 unmodified lines
546 }547 },548549 // Or show a notification only on the last retry for 5xx errors550 (request, options, response, {retryCount}) => {550 ({options, response, retryCount}) => {551 if (response.status >= 500 && response.status <= 599) {552 if (retryCount === options.retry.limit) {553 showNotification('Request failed after all retries');554 }
157 unmodified lines
712// Pass data to hooks713const api = ky.create({714 hooks: {715 beforeRequest: [716 (request, options) => {716 ({request, options}) => {717 const {token} = options.context;718 if (token) {719 request.headers.set('Authorization', `Bearer ${token}`);720 }
215 unmodified lines
936937const api = ky.extend({938 hooks: {939 afterResponse: [940 async (request, options, response) => {940 async ({request, response}) => {941 // Retry based on response body content942 if (response.status === 200) {943 const data = await response.clone().json();944
89 unmodified lines
1034```js1035await ky('https://example.com', {1036 hooks: {1037 beforeError: [1038 error => {1038 ({error}) => {1039 if (error.data !== undefined) {1040 error.message = `${error.message}: ${JSON.stringify(error.data)}`;1041 }1042
50 unmodified lines
1093const response = await ky.post(url, {1094 body: formData,1095 hooks: {1096 beforeRequest: [1097 request => {1097 ({request}) => {1098 const newFormData = new FormData();10991100 // Modify FormData as needed1101 for (const [key, value] of formData) {
178 unmodified lines
12801281const api = ky.extend({1282 hooks: {1283 beforeError: [1284 async error => {1284 async ({error}) => {1285 (error as CustomError).customProperty = 'value';1286 return error;1287 }1288 ]
74 unmodified lines