@civitas-cerebrum/wasapi

中文文档
0.0.5发布于 2026/11/01MITTypeScriptCommonJS构建来源已验证近 30 天下载 2972

A lightweight REST API client library with fluent builder, typed responses, and decorator-based API definitions.

原始使用文档
文档目录18 节
  1. Features
  2. Installation
  3. Quick Start
  4. 1. Define your API with decorators
  5. 2. Build the client
  6. 3. Execute requests
  7. API Reference
  8. Decorators
  9. @HTTP — Custom HTTP Methods
  10. WasapiClient.Builder
  11. ApiCall<T>
  12. ApiResponse<T>
  13. ResponsePair<R, E>
  14. Exceptions
  15. Logging
  16. Comparison with Java Wasapi
  17. Important Notes
  18. License

Wasapi 🌶️

npm

Wasapi is a lightweight TypeScript REST API client library that simplifies HTTP service generation using decorator-based API definitions, a fluent builder, typed responses, and smart polling utilities.

The TypeScript counterpart of wasapi for Java — same design philosophy, native TypeScript experience.

Features

  • Decorator-based API definitions — @GET, @POST, @PUT, @DELETE, @PATCH, @HTTP
  • Fluent builder — configure base URL, headers, timeouts, proxy, logging
  • Typed responses — ApiCall<T>, ApiResponse<T>, ResponsePair<R, E>
  • Strict / lenient modes — throw on failure or return null
  • Response polling — monitorResponseCode(), monitorFieldValue()
  • Zero HTTP dependencies — uses native fetch (Node 18+)
  • TC39 Stage 3 decorators — no experimentalDecorators, no reflect-metadata

Installation

npm install @civitas-cerebrum/wasapi

Quick Start

1. Define your API with decorators

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. Build the client

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. Execute requests

// 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 Reference

Decorators

DecoratorDescriptionMethod args
@GET(path)HTTP GET(pathParams?, queryParams?, options?)
@POST(path)HTTP POST(body?, pathParams?, queryParams?, options?)
@PUT(path)HTTP PUT(body?, pathParams?, queryParams?, options?)
@PATCH(path)HTTP PATCH(body?, pathParams?, queryParams?, options?)
@DELETE(path)HTTP DELETE(pathParams?, queryParams?, options?)
@HTTP(method, path, hasBody?)Custom methodpositional based on hasBody

Path parameters use :param syntax — e.g., /users/:id is substituted from pathParams: { id: '5' }.

Query parameters are appended as ?key=value from queryParams: Record<string, string>.

@HTTP — Custom HTTP Methods

For unconventional methods like PURGE, COPY, or 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

MethodDescriptionDefault
setBaseUrl(url)Base URL for all requestsrequired
setHeaders(headers)Default headers (merged per-request){}
setTimeout(seconds)Request timeout in seconds60
setLogHeaders(bool)Log request headerstrue
setLogRequestBody(bool)Log request bodyfalse
setDetailedLogging(bool)Log response bodyfalse
setFollowRedirects(bool)Follow HTTP redirectsfalse
build(ApiClass)Build typed API proxy—

Pass a ContextStore instance to the constructor to read defaults from configuration:

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>

Every decorated method returns an ApiCall<T> — a lazy request descriptor that doesn't execute until you call one of its methods:

MethodReturnsDescription
perform(strict?, printBody?, ...errorModels)Promise<T | null>Execute and return body. Strict throws on failure.
getResponse(strict?, printBody?)Promise<ApiResponse<T>>Full response wrapper with status, headers, body.
getResponsePair(ErrorClass)Promise<ResponsePair<ApiResponse<T>, E>>Response + typed error body.
monitorResponseCode(code, timeout, interval?)Promise<ApiResponse<T>>Poll until HTTP status matches.
monitorFieldValue(field, value, timeout, interval?)Promise<T>Poll until a response body field matches.
clone()ApiCall<T>Independent copy for retry/polling.

ApiResponse<T>

Property / MethodTypeDescription
statusnumberHTTP status code
statusTextstringHTTP status text
headersRecord<string, string>Response headers
okbooleanTrue if status 200-299
bodyT | nullParsed JSON body
rawBodystringRaw response text
isSuccessful()booleanSame as ok
errorBody(ErrorClass?)E | nullDeserialize error body

ResponsePair<R, E>

Property / MethodTypeDescription
responseRThe API response
errorBodyE | nullTyped error body (null on success)
isError()booleanTrue if errorBody is not null

Exceptions

ClassDescription
FailedCallExceptionThrown in strict mode on non-2xx. Has statusCode, responseBody, url.
WasapiExceptionGeneral library error (timeout, missing config, etc.)

Logging

Uses the debug package with wasapi:* namespace. Enabled by default.

# 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

Comparison with Java Wasapi

Java (Retrofit)TypeScript (this package)
@GET / @POST annotations on interface@GET / @POST decorators on class methods
retrofit.create(Service.class)builder.build(ServiceClass) — returns Proxy
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()
Extend WasapiUtilitiesNo inheritance needed — all on ApiCall<T>

Important Notes

Argument order matters. Body-bearing methods (@POST, @PUT, @PATCH) take (body, pathParams?, queryParams?, options?). Non-body methods (@GET, @DELETE) take (pathParams?, queryParams?, options?). TypeScript enforces this at compile time, but be careful when constructing calls dynamically.

perform() returns null in lenient mode for both empty successful responses (e.g., 204) and failed requests. If you need to distinguish these cases, use getResponse() which gives you the full ApiResponse<T> with status code.

Response body is a plain JSON object, not a class instance. ApiCall<User>.perform() returns a plain object shaped as User, not an instance of User with methods. This is standard TypeScript REST client behavior (same as axios, ky, etc.).

Timeout units: Builder's setTimeout() is in seconds. Polling methods (monitorResponseCode, monitorFieldValue) take milliseconds for timeout and interval.

FormData via options: To send multipart requests through the decorator path, pass formData in the options parameter:

const form = WasapiClient.getMultipartFromFile('./photo.jpg', 'avatar');
await api.uploadAvatar(undefined, undefined, { formData: form }).perform(true);

License

MIT

版本与发布记录

@civitas-cerebrum/wasapi 共发布 5 个版本,首次发布于 2026/04/06;过去 12 个月发布了 5 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.0.5latest2026/11/018 天前
0.0.42026/05/086 个月前
0.0.32026/04/067 个月前
0.0.22026/04/067 个月前
0.0.12026/04/067 个月前

关于 @civitas-cerebrum/wasapi 的常见问题

@civitas-cerebrum/wasapi 是什么?

A lightweight REST API client library with fluent builder, typed responses, and decorator-based API definitions.

如何安装 @civitas-cerebrum/wasapi?

在项目目录运行 npm install @civitas-cerebrum/wasapi,或使用 pnpm add / yarn add / bun add。

@civitas-cerebrum/wasapi 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@civitas-cerebrum/wasapi 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@civitas-cerebrum/wasapi 可以商用吗?

@civitas-cerebrum/wasapi 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@civitas-cerebrum/wasapi 的下载量有多少?

根据 npm 官方下载统计,@civitas-cerebrum/wasapi 在 2026/10/10 – 2026/11/08 这 30 天内被下载 2,972 次,日均约 99 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@civitas-cerebrum/wasapi 还在维护吗?

最新版本 0.0.5 发布于 2026/11/01(8 天前);至今共发布 5 个版本,其中过去 12 个月发布了 5 个;首次发布于 2026/04/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。