Skip to content

服务与端点

使用 TypeScript 传统装饰器把服务方法替换成 Fetcher 请求。启用 experimentalDecoratorsemitDecoratorMetadata,与本包 tsconfig 一致;stage-3 装饰器不支持此参数装饰器契约。包自身会导入 reflect-metadata。

类与方法装饰器

工厂默认值返回值
api(basePath = '', metadata = {})metadata: Omit<ApiMetadata, 'basePath'>类装饰器,绑定端点方法后返回同一构造器。
endpoint(method?, path?, metadata = {})method/path 可选记录 EndpointMetadata 的方法装饰器。
getpostputdelpatchheadoptionspath = ''metadata: MethodEndpointMetadata = {}对应 HTTP 方法装饰器,DELETE 使用 del

PathCapable 提供可选 pathEndpointMetadata 扩展 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>。钩子及失败见执行过程

完整示例

ts
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;

公开符号与源码

符号实现
ApiMetadataapiDecorator.ts:40
ApiMetadataCapableapiDecorator.ts:83
apiapiDecorator.ts:228
PathCapableendpointDecorator.ts:5
EndpointMetadataendpointDecorator.ts:21
MethodEndpointMetadataendpointDecorator.ts:33
endpointendpointDecorator.ts:59
getendpointDecorator.ts:101
postendpointDecorator.ts:126
putendpointDecorator.ts:151
delendpointDecorator.ts:176
patchendpointDecorator.ts:201
headendpointDecorator.ts:229
optionsendpointDecorator.ts:254
AutoGeneratedgenerated.ts:25
autoGeneratedErrorgenerated.ts:41

包索引

基于 Apache License 2.0 发布。