@ahoo-wang/fetcher 0.6.8 → 0.6.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,73 +1,288 @@
1
1
  import { Fetcher, FetcherRequest } from './fetcher';
2
2
  import { NamedCapable } from './types';
3
3
  import { OrderedCapable } from './orderedCapable';
4
+ /**
5
+ * FetchExchange Interface
6
+ *
7
+ * Represents the complete exchange object that flows through the interceptor chain.
8
+ * This object contains all the information about a request, response, and any errors
9
+ * that occur during the HTTP request lifecycle. It also provides a mechanism for
10
+ * sharing data between interceptors through the attributes property.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * // In a request interceptor
15
+ * const requestInterceptor: Interceptor = {
16
+ * name: 'RequestInterceptor',
17
+ * order: 0,
18
+ * async intercept(exchange: FetchExchange): Promise<FetchExchange> {
19
+ * // Add custom data to share with other interceptors
20
+ * exchange.attributes = exchange.attributes || {};
21
+ * exchange.attributes.startTime = Date.now();
22
+ * exchange.attributes.customHeader = 'my-value';
23
+ * return exchange;
24
+ * }
25
+ * };
26
+ *
27
+ * // In a response interceptor
28
+ * const responseInterceptor: Interceptor = {
29
+ * name: 'ResponseInterceptor',
30
+ * order: 0,
31
+ * async intercept(exchange: FetchExchange): Promise<FetchExchange> {
32
+ * // Access data shared by previous interceptors
33
+ * if (exchange.attributes && exchange.attributes.startTime) {
34
+ * const startTime = exchange.attributes.startTime;
35
+ * const duration = Date.now() - startTime;
36
+ * console.log(`Request took ${duration}ms`);
37
+ * }
38
+ * return exchange;
39
+ * }
40
+ * };
41
+ * ```
42
+ */
4
43
  export interface FetchExchange {
44
+ /**
45
+ * The Fetcher instance that initiated this exchange
46
+ */
5
47
  fetcher: Fetcher;
48
+ /**
49
+ * The URL for this request
50
+ */
6
51
  url: string;
52
+ /**
53
+ * The request configuration including method, headers, body, etc.
54
+ */
7
55
  request: FetcherRequest;
56
+ /**
57
+ * The response object, undefined until the request completes successfully
58
+ */
8
59
  response: Response | undefined;
60
+ /**
61
+ * Any error that occurred during the request processing, undefined if no error occurred
62
+ */
9
63
  error: Error | any | undefined;
64
+ /**
65
+ * Shared attributes for passing data between interceptors
66
+ *
67
+ * This property allows interceptors to share arbitrary data with each other.
68
+ * Interceptors can read from and write to this object to pass information
69
+ * along the interceptor chain.
70
+ *
71
+ * @remarks
72
+ * - This property is optional and may be undefined initially
73
+ * - Interceptors should initialize this property if they need to use it
74
+ * - Use string keys to avoid conflicts between different interceptors
75
+ * - Consider namespacing your keys (e.g., 'mylib.retryCount' instead of 'retryCount')
76
+ * - Be mindful of memory usage when storing large objects
77
+ */
78
+ attributes?: Record<string, any>;
10
79
  }
11
80
  /**
12
- * 拦截器接口,定义了拦截器的基本结构
13
- * @template T - 拦截器处理的数据类型
81
+ * Interceptor Interface
82
+ *
83
+ * Defines the basic structure of an interceptor. Interceptors are used to process
84
+ * requests, responses, or errors at different stages of the HTTP request lifecycle.
85
+ *
86
+ * @remarks
87
+ * Interceptors follow the Chain of Responsibility pattern, where each interceptor
88
+ * can modify the exchange object and pass it to the next interceptor in the chain.
89
+ *
90
+ * @example
91
+ * // Example of a custom request interceptor
92
+ * const loggingInterceptor: Interceptor = {
93
+ * name: 'LoggingInterceptor',
94
+ * order: 0,
95
+ * async intercept(exchange: FetchExchange): Promise<FetchExchange> {
96
+ * console.log(`Making request to ${exchange.url}`);
97
+ * const result = await next.intercept(exchange);
98
+ * console.log(`Received response with status ${result.response?.status}`);
99
+ * return result;
100
+ * }
101
+ * };
14
102
  */
15
103
  export interface Interceptor extends NamedCapable, OrderedCapable {
16
104
  /**
17
- * 拦截器的名称,用于标识拦截器,不可重复
105
+ * Interceptor name, used to identify the interceptor and must be unique
106
+ *
107
+ * @remarks
108
+ * The name is used by the InterceptorManager to manage interceptors,
109
+ * including adding, removing, and preventing duplicates.
18
110
  */
19
111
  name: string;
20
112
  /**
21
- * 拦截并处理数据
22
- * @param exchange - 需要处理的数据
23
- * @returns 处理后的数据,可以是同步或异步返回
113
+ * Intercept and process data
114
+ *
115
+ * This method is called by the InterceptorManager to process the exchange object.
116
+ * The interceptor can modify the request, response, or error properties of the
117
+ * exchange object and then pass it to the next interceptor in the chain.
118
+ *
119
+ * @param exchange - The data to be processed, containing request, response, and error information
120
+ * @returns The processed data, which can be returned synchronously or asynchronously
121
+ *
122
+ * @remarks
123
+ * Interceptors should either return the exchange object (possibly modified) or
124
+ * a new exchange object. They can also throw errors or transform errors into responses.
24
125
  */
25
126
  intercept(exchange: FetchExchange): FetchExchange | Promise<FetchExchange>;
26
127
  }
27
128
  /**
28
- * 拦截器管理器类,用于管理同一类型的多个拦截器
129
+ * InterceptorManager Class
130
+ *
131
+ * Manages multiple interceptors of the same type. Responsible for adding, removing,
132
+ * and executing interceptors in the correct order. Each InterceptorManager instance
133
+ * handles one type of interceptor (request, response, or error).
134
+ *
135
+ * @remarks
136
+ * Interceptors are executed in ascending order of their `order` property.
137
+ * Interceptors with the same order value are executed in the order they were added.
138
+ *
139
+ * @example
140
+ * // Create an interceptor manager with initial interceptors
141
+ * const requestManager = new InterceptorManager([interceptor1, interceptor2]);
142
+ *
143
+ * // Add a new interceptor
144
+ * requestManager.use(newInterceptor);
145
+ *
146
+ * // Remove an interceptor by name
147
+ * requestManager.eject('InterceptorName');
148
+ *
149
+ * // Process an exchange through all interceptors
150
+ * const result = await requestManager.intercept(exchange);
29
151
  */
30
152
  export declare class InterceptorManager implements Interceptor {
153
+ /**
154
+ * Gets the name of this interceptor manager
155
+ *
156
+ * @returns The constructor name of this class
157
+ */
31
158
  get name(): string;
159
+ /**
160
+ * Gets the order of this interceptor manager
161
+ *
162
+ * @returns Number.MIN_SAFE_INTEGER, indicating this manager should execute early
163
+ */
32
164
  get order(): number;
165
+ /**
166
+ * Array of interceptors managed by this manager, sorted by their order property
167
+ */
33
168
  private sortedInterceptors;
169
+ /**
170
+ * Creates a new InterceptorManager instance
171
+ *
172
+ * @param interceptors - Initial array of interceptors to manage
173
+ *
174
+ * @remarks
175
+ * The provided interceptors will be sorted by their order property immediately
176
+ * upon construction.
177
+ */
34
178
  constructor(interceptors?: Interceptor[]);
35
179
  /**
36
- * 添加拦截器到管理器中
37
- * @param interceptor - 要添加的拦截器
38
- * @returns 拦截器在管理器中的索引位置
180
+ * Adds an interceptor to this manager
181
+ *
182
+ * @param interceptor - The interceptor to add
183
+ * @returns True if the interceptor was added, false if an interceptor with the
184
+ * same name already exists
185
+ *
186
+ * @remarks
187
+ * Interceptors are uniquely identified by their name property. Attempting to add
188
+ * an interceptor with a name that already exists in the manager will fail.
189
+ *
190
+ * After adding, interceptors are automatically sorted by their order property.
39
191
  */
40
192
  use(interceptor: Interceptor): boolean;
41
193
  /**
42
- * 根据名称移除拦截器
43
- * @param name 要移除的拦截器名称
194
+ * Removes an interceptor by name
195
+ *
196
+ * @param name - The name of the interceptor to remove
197
+ * @returns True if an interceptor was removed, false if no interceptor with the
198
+ * given name was found
44
199
  */
45
200
  eject(name: string): boolean;
46
201
  /**
47
- * 清空所有拦截器
202
+ * Removes all interceptors from this manager
48
203
  */
49
204
  clear(): void;
50
205
  /**
51
- * 依次执行所有拦截器对数据的处理
52
- * @param exchange - 需要处理的数据
53
- * @returns 经过所有拦截器处理后的数据
206
+ * Executes all managed interceptors on the given exchange object
207
+ *
208
+ * @param exchange - The exchange object to process
209
+ * @returns A promise that resolves to the processed exchange object
210
+ *
211
+ * @remarks
212
+ * Interceptors are executed in order, with each interceptor receiving the result
213
+ * of the previous interceptor. The first interceptor receives the original
214
+ * exchange object.
215
+ *
216
+ * If any interceptor throws an error, the execution chain is broken and the error
217
+ * is propagated to the caller.
54
218
  */
55
219
  intercept(exchange: FetchExchange): Promise<FetchExchange>;
56
220
  }
57
221
  /**
58
- * Fetcher拦截器集合类,包含请求、响应和错误拦截器管理器
222
+ * FetcherInterceptors Class
223
+ *
224
+ * The interceptor collection management class for Fetcher, responsible for managing three types of interceptors:
225
+ * 1. Request interceptors - Process requests before sending HTTP requests
226
+ * 2. Response interceptors - Process responses after receiving HTTP responses
227
+ * 3. Error interceptors - Handle errors when they occur during the request process
228
+ *
229
+ * Each type of interceptor is managed by an InterceptorManager instance, supporting adding, removing, and executing interceptors.
230
+ *
231
+ * @example
232
+ * // Create a custom interceptor
233
+ * const customRequestInterceptor: Interceptor = {
234
+ * name: 'CustomRequestInterceptor',
235
+ * order: 100,
236
+ * async intercept(exchange: FetchExchange): Promise<FetchExchange> {
237
+ * // Modify request headers
238
+ * exchange.request.headers = {
239
+ * ...exchange.request.headers,
240
+ * 'X-Custom-Header': 'custom-value'
241
+ * };
242
+ * return exchange;
243
+ * }
244
+ * };
245
+ *
246
+ * // Add interceptor to Fetcher
247
+ * const fetcher = new Fetcher();
248
+ * fetcher.interceptors.request.use(customRequestInterceptor);
249
+ *
250
+ * @remarks
251
+ * By default, the request interceptor manager has two built-in interceptors registered:
252
+ * 1. RequestBodyInterceptor - Automatically converts object-type request bodies to JSON strings
253
+ * 2. FetchInterceptor - Executes actual HTTP requests and handles timeouts
59
254
  */
60
255
  export declare class FetcherInterceptors {
61
256
  /**
62
- * 请求拦截器管理器
257
+ * Request Interceptor Manager
258
+ *
259
+ * Responsible for managing all request-phase interceptors, executed before HTTP requests are sent.
260
+ * Contains two built-in interceptors by default: RequestBodyInterceptor and FetchInterceptor.
261
+ *
262
+ * @remarks
263
+ * Request interceptors are executed in ascending order of their order values, with smaller values having higher priority.
264
+ * FetchInterceptor's order is set to Number.MAX_SAFE_INTEGER to ensure it executes last.
63
265
  */
64
266
  request: InterceptorManager;
65
267
  /**
66
- * 响应拦截器管理器
268
+ * Response Interceptor Manager
269
+ *
270
+ * Responsible for managing all response-phase interceptors, executed after HTTP responses are received.
271
+ * Empty by default, custom response processing logic can be added as needed.
272
+ *
273
+ * @remarks
274
+ * Response interceptors are executed in ascending order of their order values, with smaller values having higher priority.
67
275
  */
68
276
  response: InterceptorManager;
69
277
  /**
70
- * 错误拦截器管理器
278
+ * Error Interceptor Manager
279
+ *
280
+ * Responsible for managing all error-handling phase interceptors, executed when errors occur during HTTP requests.
281
+ * Empty by default, custom error handling logic can be added as needed.
282
+ *
283
+ * @remarks
284
+ * Error interceptors are executed in ascending order of their order values, with smaller values having higher priority.
285
+ * Error interceptors can transform errors into normal responses, avoiding thrown exceptions.
71
286
  */
72
287
  error: InterceptorManager;
73
288
  }
@@ -1 +1 @@
1
- {"version":3,"file":"interceptor.d.ts","sourceRoot":"","sources":["../src/interceptor.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,cAAc,EAAY,MAAM,kBAAkB,CAAC;AAG5D,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,OAAO,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,cAAc,CAAC;IACxB,QAAQ,EAAE,QAAQ,GAAG,SAAS,CAAC;IAC/B,KAAK,EAAE,KAAK,GAAG,GAAG,GAAG,SAAS,CAAC;CAChC;AAED;;;GAGG;AACH,MAAM,WAAW,WAAY,SAAQ,YAAY,EAAE,cAAc;IAC/D;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;;;OAIG;IACH,SAAS,CAAC,QAAQ,EAAE,aAAa,GAAG,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;CAC5E;AAED;;GAEG;AACH,qBAAa,kBAAmB,YAAW,WAAW;IACpD,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,IAAI,KAAK,IAAI,MAAM,CAElB;IAED,OAAO,CAAC,kBAAkB,CAAqB;gBAEnC,YAAY,GAAE,WAAW,EAAO;IAI5C;;;;OAIG;IACH,GAAG,CAAC,WAAW,EAAE,WAAW,GAAG,OAAO;IAQtC;;;OAGG;IACH,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAM5B;;OAEG;IACH,KAAK,IAAI,IAAI;IAIb;;;;OAIG;IACG,SAAS,CAAC,QAAQ,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;CAQjE;AAED;;GAEG;AACH,qBAAa,mBAAmB;IAC9B;;OAEG;IACH,OAAO,EAAE,kBAAkB,CAA0D;IAErF;;OAEG;IACH,QAAQ,EAAE,kBAAkB,CAA4B;IAExD;;OAEG;IACH,KAAK,EAAE,kBAAkB,CAA4B;CACtD"}
1
+ {"version":3,"file":"interceptor.d.ts","sourceRoot":"","sources":["../src/interceptor.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,cAAc,EAAY,MAAM,kBAAkB,CAAC;AAI5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,MAAM,WAAW,aAAa;IAC5B;;OAEG;IACH,OAAO,EAAE,OAAO,CAAC;IAEjB;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;IAEZ;;OAEG;IACH,OAAO,EAAE,cAAc,CAAC;IAExB;;OAEG;IACH,QAAQ,EAAE,QAAQ,GAAG,SAAS,CAAC;IAE/B;;OAEG;IACH,KAAK,EAAE,KAAK,GAAG,GAAG,GAAG,SAAS,CAAC;IAE/B;;;;;;;;;;;;;OAaG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAClC;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,WAAW,WAAY,SAAQ,YAAY,EAAE,cAAc;IAC/D;;;;;;OAMG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;;;;;;;;;;;;OAaG;IACH,SAAS,CAAC,QAAQ,EAAE,aAAa,GAAG,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;CAC5E;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBAAa,kBAAmB,YAAW,WAAW;IACpD;;;;OAIG;IACH,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED;;;;OAIG;IACH,IAAI,KAAK,IAAI,MAAM,CAElB;IAED;;OAEG;IACH,OAAO,CAAC,kBAAkB,CAAqB;IAE/C;;;;;;;;OAQG;gBACS,YAAY,GAAE,WAAW,EAAO;IAI5C;;;;;;;;;;;;OAYG;IACH,GAAG,CAAC,WAAW,EAAE,WAAW,GAAG,OAAO;IAWtC;;;;;;OAMG;IACH,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAS5B;;OAEG;IACH,KAAK,IAAI,IAAI;IAIb;;;;;;;;;;;;;OAaG;IACG,SAAS,CAAC,QAAQ,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;CAQjE;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,qBAAa,mBAAmB;IAC9B;;;;;;;;;OASG;IACH,OAAO,EAAE,kBAAkB,CAGxB;IAEH;;;;;;;;OAQG;IACH,QAAQ,EAAE,kBAAkB,CAA4B;IAExD;;;;;;;;;OASG;IACH,KAAK,EAAE,kBAAkB,CAA4B;CACtD"}
@@ -1,28 +1,33 @@
1
1
  /**
2
- * 具备排序能力的接口
2
+ * OrderedCapable Interface
3
3
  *
4
- * 实现该接口的类型需要提供一个排序属性,用于确定执行顺序。
5
- * 数值越小优先级越高,相同数值的元素保持原有相对顺序。
4
+ * Interface that provides ordering capability for types that implement it.
5
+ * Implementing types must provide an order property to determine execution order.
6
+ * Lower numerical values have higher priority, and elements with the same value
7
+ * maintain their relative order.
6
8
  */
7
9
  export interface OrderedCapable {
8
10
  /**
9
- * 排序值
11
+ * Order value
10
12
  *
11
- * 数值越小优先级越高。负数、零和正数都支持。
12
- * 当多个元素具有相同的order值时,它们的相对顺序将保持不变(稳定排序)。
13
+ * Lower numerical values have higher priority. Negative numbers, zero, and
14
+ * positive numbers are all supported.
15
+ * When multiple elements have the same order value, their relative order
16
+ * will remain unchanged (stable sort).
13
17
  */
14
18
  order: number;
15
19
  }
16
20
  /**
17
- * 对实现了OrderedCapable接口的数组进行排序
21
+ * Sorts an array of elements that implement the OrderedCapable interface
18
22
  *
19
- * 该函数创建并返回一个新的排序数组,不会修改原始数组。
20
- * 支持可选的过滤函数来筛选需要排序的元素。
23
+ * This function creates and returns a new sorted array without modifying the
24
+ * original array. It supports an optional filter function to select elements
25
+ * that should participate in sorting.
21
26
  *
22
- * @template T - 数组元素类型,必须实现OrderedCapable接口
23
- * @param array - 需要排序的数组
24
- * @param filter - 可选的过滤函数,用于筛选需要参与排序的元素
25
- * @returns 排序后的新数组,按照order值升序排列
27
+ * @template T - Array element type that must implement the OrderedCapable interface
28
+ * @param array - The array to be sorted
29
+ * @param filter - Optional filter function to select elements that should be sorted
30
+ * @returns A new array sorted in ascending order by the order property
26
31
  *
27
32
  * @example
28
33
  * ```typescript
@@ -33,11 +38,11 @@ export interface OrderedCapable {
33
38
  * ];
34
39
  *
35
40
  * const sortedItems = toSorted(items);
36
- * // 结果: [{ order: 1 }, { order: 5 }, { order: 10 }]
41
+ * // Result: [{ order: 1 }, { order: 5 }, { order: 10 }]
37
42
  *
38
- * // 使用过滤函数
43
+ * // Using filter function
39
44
  * const filteredAndSorted = toSorted(items, item => item.order > 3);
40
- * // 结果: [{ order: 5 }, { order: 10 }]
45
+ * // Result: [{ order: 5 }, { order: 10 }]
41
46
  * ```
42
47
  */
43
48
  export declare function toSorted<T extends OrderedCapable>(array: T[], filter?: (item: T) => boolean): T[];
@@ -1 +1 @@
1
- {"version":3,"file":"orderedCapable.d.ts","sourceRoot":"","sources":["../src/orderedCapable.ts"],"names":[],"mappings":"AAaA;;;;;GAKG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;;OAKG;IACH,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,cAAc,EAC/C,KAAK,EAAE,CAAC,EAAE,EACV,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,OAAO,GAC5B,CAAC,EAAE,CAKL"}
1
+ {"version":3,"file":"orderedCapable.d.ts","sourceRoot":"","sources":["../src/orderedCapable.ts"],"names":[],"mappings":"AAaA;;;;;;;GAOG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;;;;OAOG;IACH,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,cAAc,EAC/C,KAAK,EAAE,CAAC,EAAE,EACV,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,OAAO,GAC5B,CAAC,EAAE,CAKL"}
@@ -1,17 +1,38 @@
1
1
  import { FetchExchange, Interceptor } from './interceptor';
2
2
  /**
3
- * 请求体拦截器,负责将普通对象转换为JSON字符串
3
+ * RequestBodyInterceptor Class
4
+ *
5
+ * Interceptor responsible for converting plain objects to JSON strings for HTTP request bodies.
6
+ * This interceptor ensures that object request bodies are properly serialized and that
7
+ * the appropriate Content-Type header is set.
8
+ *
9
+ * @remarks
10
+ * This interceptor runs early in the request processing chain with the lowest possible
11
+ * order value (Number.MIN_SAFE_INTEGER) to ensure request bodies are properly formatted
12
+ * before other interceptors process them.
4
13
  */
5
14
  export declare class RequestBodyInterceptor implements Interceptor {
15
+ /**
16
+ * Interceptor name, used for identification and management
17
+ */
6
18
  name: string;
19
+ /**
20
+ * Interceptor execution order, set to minimum safe integer to ensure early execution
21
+ *
22
+ * @remarks
23
+ * This interceptor should run before other request interceptors to ensure
24
+ * request bodies are properly formatted early in the processing chain.
25
+ */
7
26
  order: number;
8
27
  /**
9
- * 尝试转换请求体为合法的 fetch API body 类型
28
+ * Attempts to convert request body to a valid fetch API body type
29
+ *
30
+ * According to the Fetch API specification, body can be multiple types, but for
31
+ * plain objects, they need to be converted to JSON strings.
10
32
  *
11
- * 根据 Fetch API 规范,body 可以是多种类型,但对于普通对象,需要转换为 JSON 字符串
12
- * https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#setting_a_body
33
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#setting_a_body}
13
34
  *
14
- * 支持的类型:
35
+ * Supported types:
15
36
  * - a string
16
37
  * - ArrayBuffer
17
38
  * - TypedArray
@@ -22,10 +43,22 @@ export declare class RequestBodyInterceptor implements Interceptor {
22
43
  * - FormData
23
44
  * - ReadableStream
24
45
  *
25
- * 对于不支持的 object 类型(如普通对象),将自动转换为 JSON 字符串
46
+ * For unsupported object types (like plain objects), they will be automatically
47
+ * converted to JSON strings.
48
+ *
49
+ * @param exchange - The exchange object containing the request to process
50
+ * @returns The processed exchange object with potentially modified request body
26
51
  *
27
- * @param exchange
28
- * @returns 转换后的请求
52
+ * @example
53
+ * // Plain object body will be converted to JSON
54
+ * const exchange = {
55
+ * request: {
56
+ * body: { name: 'John', age: 30 }
57
+ * }
58
+ * };
59
+ * const result = interceptor.intercept(exchange);
60
+ * // result.request.body will be '{"name":"John","age":30}'
61
+ * // result.request.headers will include 'Content-Type: application/json'
29
62
  */
30
63
  intercept(exchange: FetchExchange): FetchExchange;
31
64
  }
@@ -1 +1 @@
1
- {"version":3,"file":"requestBodyInterceptor.d.ts","sourceRoot":"","sources":["../src/requestBodyInterceptor.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAG3D;;GAEG;AACH,qBAAa,sBAAuB,YAAW,WAAW;IACxD,IAAI,SAA4B;IAChC,KAAK,SAA2B;IAEhC;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,SAAS,CAAC,QAAQ,EAAE,aAAa,GAAG,aAAa;CA2ClD"}
1
+ {"version":3,"file":"requestBodyInterceptor.d.ts","sourceRoot":"","sources":["../src/requestBodyInterceptor.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAG3D;;;;;;;;;;;GAWG;AACH,qBAAa,sBAAuB,YAAW,WAAW;IACxD;;OAEG;IACH,IAAI,SAA4B;IAEhC;;;;;;OAMG;IACH,KAAK,SAA2B;IAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAmCG;IACH,SAAS,CAAC,QAAQ,EAAE,aAAa,GAAG,aAAa;CA2ClD"}
package/dist/timeout.d.ts CHANGED
@@ -1,28 +1,96 @@
1
- import { FetchExchange } from './interceptor';
2
1
  /**
3
- * 定义具有超时能力的接口
2
+ * TimeoutCapable Interface
3
+ *
4
+ * Interface that defines timeout capability for HTTP requests.
4
5
  */
5
6
  export interface TimeoutCapable {
6
7
  /**
7
- * 请求超时
8
- * 当值为0时,表示不设置超时,默认值为 undefined
8
+ * Request timeout in milliseconds
9
+ *
10
+ * When the value is 0, it indicates no timeout should be set.
11
+ * The default value is undefined.
9
12
  */
10
13
  timeout?: number;
11
14
  }
12
15
  /**
13
- * 解析请求超时设置,优先使用请求级别的超时设置
16
+ * Resolves request timeout settings, prioritizing request-level timeout settings
17
+ *
18
+ * @param requestTimeout - Request-level timeout setting
19
+ * @param optionsTimeout - Configuration-level timeout setting
20
+ * @returns Resolved timeout setting
14
21
  *
15
- * @param requestTimeout - 请求级别的超时设置
16
- * @param optionsTimeout - 配置级别的超时设置
17
- * @returns 解析后的超时设置
22
+ * @remarks
23
+ * If requestTimeout is defined, it takes precedence over optionsTimeout.
24
+ * Otherwise, optionsTimeout is returned. If both are undefined, undefined is returned.
18
25
  */
19
26
  export declare function resolveTimeout(requestTimeout?: number, optionsTimeout?: number): number | undefined;
20
27
  /**
21
- * FetchTimeoutError 异常类
22
- * 当HTTP请求超时时抛出此异常
28
+ * FetchTimeoutError Class
29
+ *
30
+ * Exception class thrown when an HTTP request times out.
31
+ * This error is thrown by the timeoutFetch function when a request exceeds its timeout limit.
32
+ *
33
+ * @example
34
+ * ```typescript
35
+ * try {
36
+ * const response = await timeoutFetch('https://api.example.com/users', {}, 1000);
37
+ * } catch (error) {
38
+ * if (error instanceof FetchTimeoutError) {
39
+ * console.log(`Request timed out after ${error.timeout}ms`);
40
+ * }
41
+ * }
42
+ * ```
23
43
  */
24
44
  export declare class FetchTimeoutError extends Error {
25
- exchange: FetchExchange;
26
- constructor(exchange: FetchExchange, timeout: number);
45
+ /**
46
+ * The URL that timed out
47
+ */
48
+ url: string;
49
+ /**
50
+ * The request options that timed out
51
+ */
52
+ request: RequestInit;
53
+ /**
54
+ * The timeout value in milliseconds
55
+ */
56
+ timeout: number;
57
+ /**
58
+ * Creates a new FetchTimeoutError instance
59
+ *
60
+ * @param url - The URL that timed out
61
+ * @param request - The request options that timed out
62
+ * @param timeout - The timeout value in milliseconds
63
+ */
64
+ constructor(url: string, request: RequestInit, timeout: number);
27
65
  }
66
+ /**
67
+ * HTTP request method with timeout control
68
+ *
69
+ * This method uses Promise.race to implement timeout control, initiating both
70
+ * fetch request and timeout Promise simultaneously. When either Promise completes,
71
+ * it returns the result or throws an exception.
72
+ *
73
+ * @param url - The URL to fetch
74
+ * @param request - The request initialization options
75
+ * @param timeout - Optional timeout in milliseconds
76
+ * @returns Promise<Response> HTTP response Promise
77
+ * @throws FetchTimeoutError Thrown when the request times out
78
+ *
79
+ * @example
80
+ * ```typescript
81
+ * // With timeout
82
+ * try {
83
+ * const response = await timeoutFetch('https://api.example.com/users', { method: 'GET' }, 5000);
84
+ * console.log('Request completed successfully');
85
+ * } catch (error) {
86
+ * if (error instanceof FetchTimeoutError) {
87
+ * console.log(`Request timed out after ${error.timeout}ms`);
88
+ * }
89
+ * }
90
+ *
91
+ * // Without timeout (delegates to regular fetch)
92
+ * const response = await timeoutFetch('https://api.example.com/users', { method: 'GET' });
93
+ * ```
94
+ */
95
+ export declare function timeoutFetch(url: string, request: RequestInit, timeout?: number): Promise<Response>;
28
96
  //# sourceMappingURL=timeout.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"timeout.d.ts","sourceRoot":"","sources":["../src/timeout.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAE9C;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAC5B,cAAc,CAAC,EAAE,MAAM,EACvB,cAAc,CAAC,EAAE,MAAM,GACtB,MAAM,GAAG,SAAS,CAKpB;AAED;;;GAGG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C,QAAQ,EAAE,aAAa,CAAC;gBAEZ,QAAQ,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM;CAUrD"}
1
+ {"version":3,"file":"timeout.d.ts","sourceRoot":"","sources":["../src/timeout.ts"],"names":[],"mappings":"AAaA;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;;OAKG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,cAAc,CAC5B,cAAc,CAAC,EAAE,MAAM,EACvB,cAAc,CAAC,EAAE,MAAM,GACtB,MAAM,GAAG,SAAS,CAKpB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;IAEZ;;OAEG;IACH,OAAO,EAAE,WAAW,CAAC;IAErB;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;;;;;OAMG;gBACS,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM;CAW/D;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,YAAY,CAChC,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,WAAW,EACpB,OAAO,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,QAAQ,CAAC,CAyCnB"}
@@ -1,37 +1,62 @@
1
1
  import { BaseURLCapable } from './types';
2
2
  /**
3
- * URL构建器类,用于构建带有路径参数和查询参数的完整URL
3
+ * UrlBuilder Class
4
+ *
5
+ * URL builder class for constructing complete URLs with path parameters and query parameters.
6
+ * This class handles URL composition, path parameter interpolation, and query string generation.
4
7
  *
5
8
  * @example
9
+ * ```typescript
6
10
  * const urlBuilder = new UrlBuilder('https://api.example.com');
7
11
  * const url = urlBuilder.build('/users/{id}', { id: 123 }, { filter: 'active' });
8
- * // 结果: https://api.example.com/users/123?filter=active
12
+ * // Result: https://api.example.com/users/123?filter=active
13
+ * ```
9
14
  */
10
15
  export declare class UrlBuilder implements BaseURLCapable {
16
+ /**
17
+ * Base URL that all constructed URLs will be based on
18
+ */
11
19
  baseURL: string;
12
20
  /**
13
- * 创建UrlBuilder实例
21
+ * Creates a UrlBuilder instance
14
22
  *
15
- * @param baseURL - 基础URL,所有构建的URL都将基于此URL
23
+ * @param baseURL - Base URL that all constructed URLs will be based on
16
24
  */
17
25
  constructor(baseURL: string);
18
26
  /**
19
- * 构建完整的URL,包括路径参数替换和查询参数添加
27
+ * Builds a complete URL, including path parameter replacement and query parameter addition
20
28
  *
21
- * @param url - 需要构建的URL路径
22
- * @param path - 路径参数对象,用于替换URL中的占位符(如{id}
23
- * @param query - 查询参数对象,将被添加到URL查询字符串中
24
- * @returns 完整的URL字符串
25
- * @throws 当路径参数中缺少必需的占位符时抛出错误
29
+ * @param url - URL path to build
30
+ * @param path - Path parameter object used to replace placeholders in the URL (e.g., {id})
31
+ * @param query - Query parameter object to be added to the URL query string
32
+ * @returns Complete URL string
33
+ * @throws Error when required path parameters are missing
34
+ *
35
+ * @example
36
+ * ```typescript
37
+ * const urlBuilder = new UrlBuilder('https://api.example.com');
38
+ * const url = urlBuilder.build('/users/{id}/posts/{postId}',
39
+ * { id: 123, postId: 456 },
40
+ * { filter: 'active', limit: 10 }
41
+ * );
42
+ * // Result: https://api.example.com/users/123/posts/456?filter=active&limit=10
43
+ * ```
26
44
  */
27
45
  build(url: string, path?: Record<string, any>, query?: Record<string, any>): string;
28
46
  /**
29
- * 替换url中的占位符参数
47
+ * Replaces placeholders in the URL with path parameters
48
+ *
49
+ * @param url - Path string containing placeholders, e.g., "http://localhost/users/{id}/posts/{postId}"
50
+ * @param path - Path parameter object used to replace placeholders in the URL
51
+ * @returns Path string with placeholders replaced
52
+ * @throws Error when required path parameters are missing
30
53
  *
31
- * @param url - 包含占位符的路径字符串,如 "http://localhost/users/{id}/posts/{postId}"
32
- * @param path - 路径参数对象,用于替换路径中的占位符
33
- * @returns 替换占位符后的路径字符串
34
- * @throws 当路径参数中缺少必需的占位符时抛出错误
54
+ * @example
55
+ * ```typescript
56
+ * const urlBuilder = new UrlBuilder('https://api.example.com');
57
+ * const result = urlBuilder.interpolateUrl('/users/{id}/posts/{postId}', { id: 123, postId: 456 });
58
+ * // Result: /users/123/posts/456
59
+ * ```
35
60
  */
36
61
  interpolateUrl(url: string, path?: Record<string, any>): string;
37
62
  }
@@ -1 +1 @@
1
- {"version":3,"file":"urlBuilder.d.ts","sourceRoot":"","sources":["../src/urlBuilder.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC;;;;;;;GAOG;AACH,qBAAa,UAAW,YAAW,cAAc;IAC/C,OAAO,EAAE,MAAM,CAAC;IAEhB;;;;OAIG;gBACS,OAAO,EAAE,MAAM;IAI3B;;;;;;;;OAQG;IACH,KAAK,CACH,GAAG,EAAE,MAAM,EACX,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC1B,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC1B,MAAM;IAYT;;;;;;;OAOG;IACH,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM;CAWhE"}
1
+ {"version":3,"file":"urlBuilder.d.ts","sourceRoot":"","sources":["../src/urlBuilder.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC;;;;;;;;;;;;GAYG;AACH,qBAAa,UAAW,YAAW,cAAc;IAC/C;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;;;OAIG;gBACS,OAAO,EAAE,MAAM;IAI3B;;;;;;;;;;;;;;;;;;OAkBG;IACH,KAAK,CACH,GAAG,EAAE,MAAM,EACX,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC1B,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC1B,MAAM;IAYT;;;;;;;;;;;;;;OAcG;IACH,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM;CAWhE"}