瓦萨皮..
瓦萨皮 是一个轻量级的TypeScript REST API客户端库,它使用基于装饰器的API定义来简化HTTP服务生成,是一个流畅的构建器,打入的响应,以及智能的投票公用设施.
类型脚本对应的 java 时尚 ——同作设计哲学,本土TypeScript体验.
特征
- 基于装饰器的 API 定义 —— 说
@GET, (中文(简体) ),@POST, (中文(简体) ),@PUT, (中文(简体) ),@DELETE, (中文(简体) ),@PATCH, (中文(简体) ),@HTTP - 流利的建设者 ——配置基础 URL,信头,超时,代理,日志
- 输入的答复 —— 说
ApiCall<T>, (中文(简体) ),ApiResponse<T>, (中文(简体) ),ResponsePair<R, E> - 严格/宽大模式 - 投出失败或返回无效
- 反应投票 —— 说
monitorResponseCode(), (中文(简体) ),monitorFieldValue() - 零 HTTP 依赖性 - 使用本地语言
fetch(节点18+) - TC39 第3阶段装饰器 没有
experimentalDecorators,没有reflect-metadata
安装
npm install @civitas-cerebrum/wasapi
快速启动
1. 用装饰器定义您的 API
import { GET, POST, DELETE, ApiCall } from '@civitas-cerebrum/wasapi';
interface User {
id: string;
name: string;
email: string;
}
class UserApi {
@GET('/users')
getUsers(): ApiCall<User[]> { return null!; }
@GET('/users/:id')
getUser(pathParams: { id: string }): ApiCall<User> { return null!; }
@POST('/users')
createUser(body: { name: string; email: string }): ApiCall<User> { return null!; }
@DELETE('/users/:id')
deleteUser(pathParams: { id: string }): ApiCall<void> { return null!; }
}
2. 构建客户端
import { WasapiClient } from '@civitas-cerebrum/wasapi';
const api = new WasapiClient.Builder()
.setBaseUrl('https://api.example.com')
.setHeaders({ Authorization: 'Bearer token' })
.setLogHeaders(true)
.build(UserApi);
3. 执行请求
// Lenient mode (default) — returns null on failure
const users = await api.getUsers().perform();
// Strict mode — throws FailedCallException on non-2xx
const users = await api.getUsers().perform(true);
// Strict + log response body
const users = await api.getUsers().perform(true, true);
// Full response wrapper
const response = await api.getUser({ id: '5' }).getResponse();
console.log(response.status); // 200
console.log(response.body); // User object
console.log(response.headers); // Record<string, string>
// Typed error handling
const pair = await api.getUser({ id: 'bad' }).getResponsePair(ErrorModel);
if (pair.isError()) {
console.log(pair.errorBody); // ErrorModel instance
}
API 参考
装饰者
| 装饰 | 说明 | 方法参数 |
|---|---|---|
@GET(path) | HTTP 获取 | (pathParams?, queryParams?, options?) |
@POST(path) | HTTP 邮编 | (body?, pathParams?, queryParams?, options?) |
@PUT(path) | HTTP PUT 软件 | (body?, pathParams?, queryParams?, options?) |
@PATCH(path) | 哈特普・帕奇 | (body?, pathParams?, queryParams?, options?) |
@DELETE(path) | HTTP 抖音 | (pathParams?, queryParams?, options?) |
@HTTP(method, path, hasBody?) | 自定义方法 | 基于 hasBody |
路径参数 使用情况 :param 语法——例如, /users/:id 替换为 pathParams: { id: '5' }。 。 。 .
查询参数 后附为 ?key=value 从 queryParams: Record<string, string>。 。 。 .
@HTTP - 自定义HTTP方法
对于非常规方法,如 PURGE, (中文(简体) ), COPY,或 LOCK数字 :
import { HTTP, ApiCall } from '@civitas-cerebrum/wasapi';
class CacheApi {
@HTTP('PURGE', '/cache/:key')
purge(pathParams: { key: string }): ApiCall<void> { return null!; }
@HTTP('REPORT', '/analytics', true) // hasBody = true
report(body: ReportRequest): ApiCall<ReportResult> { return null!; }
}
WasapiClient.Builder
| 方法 | 说明 | 默认 |
|---|---|---|
setBaseUrl(url) | 所有请求的基准 URL | 所需经费 |
setHeaders(headers) | 默认信头( 按请求合并) | {} |
setTimeout(seconds) | 请求超时( 秒) | 60 |
setLogHeaders(bool) | 日志请求信头 | true |
setLogRequestBody(bool) | 日志请求正文 | false |
setDetailedLogging(bool) | 日志响应机构 | false |
setFollowRedirects(bool) | 跟随 HTTP 重定向 | false |
build(ApiClass) | 构建已键入的 API 代理 | —— 说 |
传出 a ContextStore 实例到构建器从配置中读取默认值 :
const store = new ContextStore();
store.put('wasapi.baseUrl', 'https://api.example.com');
store.put('wasapi.timeout', 30);
const api = new WasapiClient.Builder(store).build(MyApi);
ApiCall<T>
每个装饰方法返回一个 ApiCall<T> 一个懒惰的要求描述器,它不会执行 直到你调用它的方法之一:
| 方法 | 回返 | 说明 |
|---|---|---|
perform(strict?, printBody?, ...errorModels) | Promise<T | null> | 执行并还身. 严格投出失败. |
getResponse(strict?, printBody?) | Promise<ApiResponse<T>> | 完全反应包装 状态,标题,身体. |
getResponsePair(ErrorClass) | Promise<ResponsePair<ApiResponse<T>, E>> | 反应+打出错误正文. |
monitorResponseCode(code, timeout, interval?) | Promise<ApiResponse<T>> | 在 HTTP 状态匹配前进行投票 . |
monitorFieldValue(field, value, timeout, interval?) | Promise<T> | 直到反应体场对齐为止. |
clone() | ApiCall<T> | 独立副本,供重试/抽取. |
ApiResponse<T>
| 财产/方法 | 类型 | 说明 |
|---|---|---|
status | number | HTTP 状态代码 |
statusText | string | HTTP 状态文本 |
headers | Record<string, string> | 答复信头 |
ok | boolean | 若状态为 True, 200 - 299 |
body | T | null | 解析过的JSON体 |
rawBody | string | 原始响应文本 |
isSuccessful() | boolean | 与 ok |
errorBody(ErrorClass?) | E | null | 淡化错误正文 |
ResponsePair<R, E>
| 财产/方法 | 类型 | 说明 |
|---|---|---|
response | R | API的回应 |
errorBody | E | null | 已键入出错正文( 成功时未显示) |
isError() | boolean | 如果错误Body不是无效, 则为真 |
例外
| 类 | 说明 |
|---|---|
FailedCallException | 在非-2xx上投入了严格模式. 有过 statusCode, (中文(简体) ), responseBody, (中文(简体) ), url。 。 。 . |
WasapiException | 一般库出错( 超时出错, 缺少配置等) |
日志
使用 debug 软件包 wasapi:* 名称空间。 默认启用 .
# Suppress all wasapi logs
WASAPI_DEBUG=false npx tsx tests/my-test.ts
# Show only request logs
DEBUG=wasapi:request npx tsx tests/my-test.ts
与 Java Wasapi 的比较
| 爪哇语 (Retrofit) | 类型脚本( 此软件包) |
|---|---|
@GET 编号 : @POST 关于接口的说明 | @GET 编号 : @POST 关于类方法的装饰器 |
retrofit.create(Service.class) | builder.build(ServiceClass) ——返回代理服务器 |
Call<T> | ApiCall<T> |
Response<T> | ApiResponse<T> |
ResponsePair<R, E> | ResponsePair<R, E> |
Caller.perform(call, strict, printBody) | apiCall.perform(strict, printBody) |
WasapiUtilities.monitorResponseCode() | apiCall.monitorResponseCode() |
扩展 WasapiUtilities | 不需要继承 ApiCall<T> |
重要说明
辩相令事. 含体方法(@POST, (中文(简体) ), @PUT, (中文(简体) ), @PATCH采取 (body, pathParams?, queryParams?, options?). 非机构方法@GET, (中文(简体) ), @DELETE采取 (pathParams?, queryParams?, options?)。TypeScript在编译时执行,但在动态构建调用时要小心.
perform() 返回时 null 宽大模式 对于空成功响应(如204)和失败请求。 如果您需要区分这些案件,请使用 getResponse() 使你饱满 ApiResponse<T> 有状态代码.
反应体是普通的 JSON 对象而不是一个阶级的例子. ApiCall<User>.perform() 返回形状为 User,没有实例 User 还有方法 这是标准的 TypeScript REST 客户端行为(与 arxios, ky等相同).
超时单位 : 构建器 setTimeout() 进入 秒数投票方法monitorResponseCode, (中文(简体) ), monitorFieldValue采取 毫秒 暂停和间隔.
通过选项格式数据 : 要通过装饰器路径发送多段请求, 请通过 formData 选项参数中:
const form = WasapiClient.getMultipartFromFile('./photo.jpg', 'avatar');
await api.uploadAvatar(undefined, undefined, { formData: form }).perform(true);
许可证
麻省理工学院