feat: 创建类型化 API 客户端

This commit is contained in:
que01 committed 2026-09-19 01:11:27 +08:00
1 parent 02554ed86c
commit b9939fe173
6 files changed
+174 -3

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { ApiClient, ApiClientError, type FetchResponse } from "../src/index.js";
function response(body: unknown, status = 200): FetchResponse {
return { status, ok: status >= 200 && status < 300, json: async () => body };
}
test("客户端发送认证头、查询参数和 JSON 请求体", async () => {
const calls: Array<{ url: string; init?: { headers?: Record<string, string>; body?: string } }> = [];
const client = new ApiClient({
baseUrl: "http://api.test/",
token: "token-1",
fetcher: async (url, init) => {
calls.push({ url, init });
return response({ count: 2 });
},
});
await client.listAdminBookings({ status: "received", unreadOnly: true, tagId: "tag/1" });
await client.createAdminTag("重点");
assert.equal(calls[0]?.url, "http://api.test/admin/bookings?status=received&unreadOnly=true&tagId=tag%2F1");
assert.equal(calls[0]?.init?.headers?.authorization, "Bearer token-1");
assert.equal(calls[1]?.init?.body, JSON.stringify({ name: "重点" }));
});
test("客户端将统一错误响应转换为 ApiClientError", async () => {
const client = new ApiClient({
baseUrl: "http://api.test",
fetcher: async () => response({ data: null, error: { code: "HTTP_401", message: "无权限" }, requestId: "req-1" }, 401),
});
await assert.rejects(
() => client.getAdminUnreadCount(),
(error: unknown) => {
assert.ok(error instanceof ApiClientError);
assert.equal(error.status, 401);
assert.equal(error.code, "HTTP_401");
assert.equal(error.requestId, "req-1");
return true;
},
);
});
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "../tsconfig.json",
"compilerOptions": { "noEmit": true, "rootDir": ".." },
"include": ["./**/*.ts"]
}