@ahoo-wang/fetcher-decorator 2.9.2 → 2.9.5

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.
package/README.md CHANGED
@@ -156,9 +156,9 @@ Defines API metadata for a class.
156
156
 
157
157
  - `basePath`: Base path for all endpoints in the class
158
158
  - `metadata`: Additional metadata for the API
159
- - `headers`: Default headers for all requests in the class
160
- - `timeout`: Default timeout for all requests in the class
161
- - `fetcher`: Name of the fetcher instance to use (default: 'default')
159
+ - `headers`: Default headers for all requests in the class
160
+ - `timeout`: Default timeout for all requests in the class
161
+ - `fetcher`: Name of the fetcher instance to use (default: 'default')
162
162
 
163
163
  **Example:**
164
164
 
@@ -207,9 +207,9 @@ Defines an OPTIONS endpoint.
207
207
 
208
208
  - `path`: Path for the endpoint (relative to class base path)
209
209
  - `metadata`: Additional metadata for the endpoint
210
- - `headers`: Headers for the request
211
- - `timeout`: Timeout for the request
212
- - `fetcher`: Name of the fetcher instance to use
210
+ - `headers`: Headers for the request
211
+ - `timeout`: Timeout for the request
212
+ - `fetcher`: Name of the fetcher instance to use
213
213
 
214
214
  **Example:**
215
215
 
@@ -291,6 +291,87 @@ class UserService {
291
291
  }
292
292
  ```
293
293
 
294
+ ## 🪝 Lifecycle Hooks
295
+
296
+ The `ExecuteLifeCycle` interface allows you to hook into the request execution lifecycle and modify the `FetchExchange` before and after it is processed by interceptors. This provides a way to customize the behavior of API calls at specific points in the execution flow.
297
+
298
+ ### ExecuteLifeCycle Interface
299
+
300
+ ```typescript
301
+ import { ExecuteLifeCycle } from '@ahoo-wang/fetcher-decorator';
302
+
303
+ interface ExecuteLifeCycle {
304
+ beforeExecute?(exchange: FetchExchange): void | Promise<void>;
305
+ afterExecute?(exchange: FetchExchange): void | Promise<void>;
306
+ }
307
+ ```
308
+
309
+ ### Lifecycle Methods
310
+
311
+ #### `beforeExecute(exchange: FetchExchange)`
312
+
313
+ Called before the `FetchExchange` is processed by interceptors. Users can inspect or modify the exchange before processing, such as adding headers, modifying the request body, or setting up logging.
314
+
315
+ **Parameters:**
316
+
317
+ - `exchange`: The `FetchExchange` object representing the request and response
318
+
319
+ #### `afterExecute(exchange: FetchExchange)`
320
+
321
+ Called after the `FetchExchange` is processed by interceptors. Users can inspect or modify the exchange after processing, such as handling response data, logging results, or performing cleanup.
322
+
323
+ **Parameters:**
324
+
325
+ - `exchange`: The `FetchExchange` object representing the request and response
326
+
327
+ ### Usage Example
328
+
329
+ ```typescript
330
+ import { api, get, path, ExecuteLifeCycle } from '@ahoo-wang/fetcher-decorator';
331
+ import { FetchExchange } from '@ahoo-wang/fetcher';
332
+
333
+ @api('/users')
334
+ class UserService implements ExecuteLifeCycle {
335
+ @get('/{id}')
336
+ getUser(@path() id: number): Promise<User> {
337
+ throw autoGeneratedError(id);
338
+ }
339
+
340
+ async beforeExecute(exchange: FetchExchange): Promise<void> {
341
+ // Add custom headers before request execution
342
+ exchange.request.headers.set('X-Custom-Header', 'value');
343
+
344
+ // Log the request
345
+ console.log('Executing request:', exchange.request.url);
346
+ }
347
+
348
+ async afterExecute(exchange: FetchExchange): Promise<void> {
349
+ // Log the response status
350
+ console.log('Response status:', exchange.response?.status);
351
+
352
+ // Handle specific error codes
353
+ if (exchange.response?.status === 401) {
354
+ // Handle unauthorized access
355
+ console.warn('Unauthorized access detected');
356
+ }
357
+ }
358
+ }
359
+
360
+ const userService = new UserService();
361
+ const user = await userService.getUser(123); // Lifecycle hooks will be called automatically
362
+ ```
363
+
364
+ ### Execution Flow
365
+
366
+ When a decorated method is called, the execution follows this sequence:
367
+
368
+ 1. **Parameter Resolution**: Method arguments are resolved into request configuration
369
+ 2. **Exchange Creation**: A `FetchExchange` object is created
370
+ 3. **Before Execute Hook**: `beforeExecute` is called if implemented
371
+ 4. **Interceptor Processing**: The exchange is processed through the interceptor chain
372
+ 5. **After Execute Hook**: `afterExecute` is called if implemented
373
+ 6. **Result Extraction**: The final result is extracted and returned
374
+
294
375
  ## 🛠️ Advanced Usage
295
376
 
296
377
  ### Inheritance Support
package/README.zh-CN.md CHANGED
@@ -286,6 +286,87 @@ class UserService {
286
286
  }
287
287
  ```
288
288
 
289
+ ## 🪝 生命周期钩子
290
+
291
+ `ExecuteLifeCycle` 接口允许您钩入请求执行生命周期,并在拦截器处理 `FetchExchange` 之前和之后修改它。这提供了一种在执行流程的特定点自定义 API 调用行为的方法。
292
+
293
+ ### ExecuteLifeCycle 接口
294
+
295
+ ```typescript
296
+ import { ExecuteLifeCycle } from '@ahoo-wang/fetcher-decorator';
297
+
298
+ interface ExecuteLifeCycle {
299
+ beforeExecute?(exchange: FetchExchange): void | Promise<void>;
300
+ afterExecute?(exchange: FetchExchange): void | Promise<void>;
301
+ }
302
+ ```
303
+
304
+ ### 生命周期方法
305
+
306
+ #### `beforeExecute(exchange: FetchExchange)`
307
+
308
+ 在 `FetchExchange` 被拦截器处理之前调用。用户可以在处理之前检查或修改交换,例如添加头部、修改请求体或设置日志记录。
309
+
310
+ **参数:**
311
+
312
+ - `exchange`: 表示请求和响应的 `FetchExchange` 对象
313
+
314
+ #### `afterExecute(exchange: FetchExchange)`
315
+
316
+ 在 `FetchExchange` 被拦截器处理之后调用。用户可以在处理之后检查或修改交换,例如处理响应数据、记录结果或执行清理。
317
+
318
+ **参数:**
319
+
320
+ - `exchange`: 表示请求和响应的 `FetchExchange` 对象
321
+
322
+ ### 使用示例
323
+
324
+ ```typescript
325
+ import { api, get, path, ExecuteLifeCycle } from '@ahoo-wang/fetcher-decorator';
326
+ import { FetchExchange } from '@ahoo-wang/fetcher';
327
+
328
+ @api('/users')
329
+ class UserService implements ExecuteLifeCycle {
330
+ @get('/{id}')
331
+ getUser(@path() id: number): Promise<User> {
332
+ throw autoGeneratedError(id);
333
+ }
334
+
335
+ async beforeExecute(exchange: FetchExchange): Promise<void> {
336
+ // 在请求执行前添加自定义头部
337
+ exchange.request.headers.set('X-Custom-Header', 'value');
338
+
339
+ // 记录请求
340
+ console.log('Executing request:', exchange.request.url);
341
+ }
342
+
343
+ async afterExecute(exchange: FetchExchange): Promise<void> {
344
+ // 记录响应状态
345
+ console.log('Response status:', exchange.response?.status);
346
+
347
+ // 处理特定错误代码
348
+ if (exchange.response?.status === 401) {
349
+ // 处理未授权访问
350
+ console.warn('Unauthorized access detected');
351
+ }
352
+ }
353
+ }
354
+
355
+ const userService = new UserService();
356
+ const user = await userService.getUser(123); // 生命周期钩子将被自动调用
357
+ ```
358
+
359
+ ### 执行流程
360
+
361
+ 当调用装饰方法时,执行遵循以下序列:
362
+
363
+ 1. **参数解析**:方法参数被解析为请求配置
364
+ 2. **交换创建**:创建 `FetchExchange` 对象
365
+ 3. **执行前钩子**:如果实现,则调用 `beforeExecute`
366
+ 4. **拦截器处理**:交换通过拦截器链处理
367
+ 5. **执行后钩子**:如果实现,则调用 `afterExecute`
368
+ 6. **结果提取**:提取并返回最终结果
369
+
289
370
  ## 🛠️ 高级用法
290
371
 
291
372
  ### 继承支持
@@ -0,0 +1,28 @@
1
+ import { FetchExchange } from '@ahoo-wang/fetcher';
2
+ /**
3
+ * Lifecycle hooks for decorator-based API execution.
4
+ *
5
+ * This interface allows users to hook into the request execution lifecycle
6
+ * and modify the FetchExchange before and after it is processed by interceptors.
7
+ * It provides a way to customize the behavior of API calls at specific points
8
+ * in the execution flow.
9
+ */
10
+ export interface ExecuteLifeCycle {
11
+ /**
12
+ * Called before the FetchExchange is processed by interceptors.
13
+ * Users can inspect or modify the exchange before processing at this point,
14
+ * such as adding headers, modifying the request body, or setting up logging.
15
+ *
16
+ * @param exchange - The FetchExchange object representing the request and response
17
+ */
18
+ beforeExecute?(exchange: FetchExchange): void | Promise<void>;
19
+ /**
20
+ * Called after the FetchExchange is processed by interceptors.
21
+ * Users can inspect or modify the exchange after processing at this point,
22
+ * such as handling response data, logging results, or performing cleanup.
23
+ *
24
+ * @param exchange - The FetchExchange object representing the request and response
25
+ */
26
+ afterExecute?(exchange: FetchExchange): void | Promise<void>;
27
+ }
28
+ //# sourceMappingURL=executeLifeCycle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executeLifeCycle.d.ts","sourceRoot":"","sources":["../src/executeLifeCycle.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD;;;;;;;GAOG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;;;;OAMG;IACH,aAAa,CAAC,CAAC,QAAQ,EAAE,aAAa,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE9D;;;;;;OAMG;IACH,YAAY,CAAC,CAAC,QAAQ,EAAE,aAAa,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9D"}