服务与端点
使用 TypeScript 传统装饰器把服务方法替换成 Fetcher 请求。启用 experimentalDecorators、emitDecoratorMetadata,与本包 tsconfig 一致;stage-3 装饰器不支持此参数装饰器契约。包自身会导入 reflect-metadata。
类与方法装饰器
| 工厂 | 默认值 | 返回值 |
|---|---|---|
api(basePath = '', metadata = {}) | metadata: Omit<ApiMetadata, 'basePath'> | 类装饰器,绑定端点方法后返回同一构造器。 |
endpoint(method?, path?, metadata = {}) | method/path 可选 | 记录 EndpointMetadata 的方法装饰器。 |
get、post、put、del、patch、head、options | path = '',metadata: MethodEndpointMetadata = {} | 对应 HTTP 方法装饰器,DELETE 使用 del。 |
PathCapable 提供可选 path。EndpointMetadata 扩展 ApiMetadata,增加可选 path/method;MethodEndpointMetadata 排除这两个字段。TRACE 使用 endpoint(HttpMethod.TRACE, path),仍受原生 Fetch 限制;没有导出的 trace 装饰器。
AutoGenerated 是消息为 'Implementation will be generated automatically.' 的 Error。autoGeneratedError(...ignored) 返回新实例,本身不抛出。类型化占位方法应写 throw autoGeneratedError(...)。如果没有成功执行 @api 绑定,它会真实抛错;仅有返回类型不会实现请求。
API 元数据与优先级
ApiMetadata 字段 | 解析规则 |
|---|---|
basePath?: string | 端点真值覆盖 API 路径,再回退空值。 |
fetcher?: string | Fetcher | 端点非 nullish 值优先,再 API,通过 getFetcher 解析。 |
headers? / urlParams? | 客户端默认值(头)、API、端点、绑定参数/request 值依次覆盖;头忽略大小写。 |
timeout?: number | 端点已定义值(含零)、API、客户端默认值依次回退。 |
resultExtractor? | 端点、API、JsonResultExtractor。 |
returnType? | 端点、API、EndpointReturnType.RESULT。 |
attributes? | API 条目、端点条目、参数属性依次覆盖。 |
ApiMetadataCapable.apiMetadata 支持实例配置。在每个方法首次调用时,buildRequestExecutor 将实例元数据浅展开覆盖装饰器元数据,并按方法名在实例缓存执行器。必须在调用前设置实例元数据,后续替换不是受支持的动态重配置机制;端点元数据仍优先。浅合并意味着实例 headers 对象先整体替换类 headers,再参与端点/请求合并。
装饰器默认返回已解析 JSON,而 Fetcher.get 默认返回 Response。HEAD/204 或原始响应选择 ResultExtractors.Response;诊断场景使用 returnType: EndpointReturnType.EXCHANGE 并声明 Promise<FetchExchange>。钩子及失败见执行过程。
完整示例
import { Fetcher } from '@ahoo-wang/fetcher';
import {
api,
get,
path,
autoGeneratedError,
} from '@ahoo-wang/fetcher-decorator';
type User = { id: string; name: string };
const client = new Fetcher({
baseURL: 'https://api.example.com',
timeout: 3000,
});
@api('/users', { fetcher: client })
class Users {
@get('/{id}')
find(@path('id') id: string): Promise<User> {
throw autoGeneratedError(id);
}
}
const users = new Users();
// Requires a service returning JSON at https://api.example.com/users/1.
async function loadUser() {
return await users.find('1');
}
void loadUser;公开符号与源码
| 符号 | 实现 |
|---|---|
ApiMetadata | apiDecorator.ts:40 |
ApiMetadataCapable | apiDecorator.ts:83 |
api | apiDecorator.ts:228 |
PathCapable | endpointDecorator.ts:5 |
EndpointMetadata | endpointDecorator.ts:21 |
MethodEndpointMetadata | endpointDecorator.ts:33 |
endpoint | endpointDecorator.ts:59 |
get | endpointDecorator.ts:101 |
post | endpointDecorator.ts:126 |
put | endpointDecorator.ts:151 |
del | endpointDecorator.ts:176 |
patch | endpointDecorator.ts:201 |
head | endpointDecorator.ts:229 |
options | endpointDecorator.ts:254 |
AutoGenerated | generated.ts:25 |
autoGeneratedError | generated.ts:41 |
