UNPKG

5.33 kBTypeScriptView Raw
1import { type stop } from '../core/constants.js';
2import type { KyRequest, KyResponse, HTTPError } from '../index.js';
3import type { NormalizedOptions } from './options.js';
4export type BeforeRequestHook = (request: KyRequest, options: NormalizedOptions) => Request | Response | void | Promise<Request | Response | void>;
5export type BeforeRetryState = {
6 request: KyRequest;
7 options: NormalizedOptions;
8 error: Error;
9 retryCount: number;
10};
11export type BeforeRetryHook = (options: BeforeRetryState) => typeof stop | void | Promise<typeof stop | void>;
12export type AfterResponseHook = (request: KyRequest, options: NormalizedOptions, response: KyResponse) => Response | void | Promise<Response | void>;
13export type BeforeErrorHook = (error: HTTPError) => HTTPError | Promise<HTTPError>;
14export type Hooks = {
15 /**
16 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 normalized input and options as arguments. You could, for example, modify `options.headers` here.
17
18 A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) can be returned from this hook to completely avoid making a 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**.
19
20 @default []
21 */
22 beforeRequest?: BeforeRequestHook[];
23 /**
24 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.
25
26 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`.
27
28 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).
29
30 @example
31 ```
32 import ky from 'ky';
33
34 const response = await ky('https://example.com', {
35 hooks: {
36 beforeRetry: [
37 async ({request, options, error, retryCount}) => {
38 const token = await ky('https://example.com/refresh-token');
39 options.headers.set('Authorization', `token ${token}`);
40 }
41 ]
42 }
43 });
44 ```
45
46 @default []
47 */
48 beforeRetry?: BeforeRetryHook[];
49 /**
50 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).
51
52 @default []
53
54 @example
55 ```
56 import ky from 'ky';
57
58 const response = await ky('https://example.com', {
59 hooks: {
60 afterResponse: [
61 (_input, _options, response) => {
62 // You could do something with the response, for example, logging.
63 log(response);
64
65 // Or return a `Response` instance to overwrite the response.
66 return new Response('A different response', {status: 200});
67 },
68
69 // Or retry with a fresh token on a 403 error
70 async (input, options, response) => {
71 if (response.status === 403) {
72 // Get a fresh token
73 const token = await ky('https://example.com/token').text();
74
75 // Retry with the token
76 options.headers.set('Authorization', `token ${token}`);
77
78 return ky(input, options);
79 }
80 }
81 ]
82 }
83 });
84 ```
85 */
86 afterResponse?: AfterResponseHook[];
87 /**
88 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`.
89
90 @default []
91
92 @example
93 ```
94 import ky from 'ky';
95
96 await ky('https://example.com', {
97 hooks: {
98 beforeError: [
99 error => {
100 const {response} = error;
101 if (response && response.body) {
102 error.name = 'GitHubError';
103 error.message = `${response.body.message} (${response.status})`;
104 }
105
106 return error;
107 }
108 ]
109 }
110 });
111 ```
112 */
113 beforeError?: BeforeErrorHook[];
114};