@alt-stack/http-client-core
运算中性请求验证,响应打字,重试,记录,以及Altstack TypeScript HTTP客户端的错误.
大多数应用程序应安装 @alt-stack/http-client-fetch 或者说 @alt-stack/http-client-ky,它提供了执行器并重新导出此包.
安装
pnpm add @alt-stack/http-client-core zod
Zod 4是作为同伴的要求.
最小自定义执行器
import { ApiClient, type HttpExecutor } from "@alt-stack/http-client-core";
import { z } from "zod";
const Request = { "/health": { GET: {} } } as const;
const Response = {
"/health": { GET: { "200": z.object({ ok: z.boolean() }) } },
} as const;
const executor: HttpExecutor<{ requestId: string }> = {
async execute(request) {
return {
status: 200,
statusText: "OK",
data: { ok: true },
raw: { requestId: request.url },
};
},
};
const client = new ApiClient({
baseUrl: "https://api.example.test",
Request,
Response,
executor,
});
const result = await client.get("/health", {});
执行者拥有I/O,超时执行,并解码. 核心验证请求/答复计划,并将记录的HTTP地位视为受歧视的结合.
每个请求标题
客户一级 headers 选项接受 Record<string, unknown> 或返回该记录的函数,同步或作为 Promise数字 :
const client = new ApiClient({
baseUrl: "https://api.example.test",
Request,
Response,
executor,
headers: async () => ({ Authorization: `Bearer ${await getToken()}` }),
});
await client.get("/health", { headers: { "X-Request-Id": "request-123" } });
提供您的申请 getToken 函数。 提供者每次尝试运行一次,包括在请求验证后进行核心重试. 标题按此顺序合并: 默认 Content-Type: application/json 当 JSON 天体被发送时,客户头,然后请求头. 没有机构的请求没有默认 Content-Type。数值被字符串化; null 财务报告和审定财务报表 undefined 未删除早先的数值。 键保留其现有的对大小写敏感的合并行为.
投出或拒绝的提供者错误成为 UnexpectedApiClientError 带消息 Header provider failed。其原始消息和原因将被丢弃,以免出现错误和日志。 现行重试规则适用. 执行人的请求超时不涵盖供应商.