@alt-stack/http-client-fetch
使用标准获取API键入了Zod后置的HTTP客户端. 成功和记录的错误反应包括: Response 作为 raw。 。 。 .
安装
pnpm add @alt-stack/http-client-fetch zod
使用 Zod 4 和运行时间 fetch, (中文(简体) ), Response, (中文(简体) ), Headers,以及 AbortController (Node.js 18+,现代浏览器,或Bun).
快速使用
import { createApiClient } from "@alt-stack/http-client-fetch";
import { Request, Response } from "./generated-api.js";
const api = createApiClient({
baseUrl: "http://127.0.0.1:3000",
Request,
Response,
fetchOptions: { credentials: "include" },
});
const result = await api.get("/users/{id}", { params: { id: "u_1" } });
if (result.success) console.log(result.body, result.raw.status);
Request 财务报告和审定财务报表 Response 可以通过 @alt-stack/zod-openapi。获取选项不能覆盖执行器拥有的方法、标题、正文或信号.
自定义获取和认证信头
import { customFetch, getToken } from "./runtime.js";
const api = createApiClient({
baseUrl: "https://api.example.test",
Request,
Response,
fetch: customFetch,
headers: async () => ({ Authorization: `Bearer ${await getToken()}` }),
});
await api.get("/users/{id}", {
params: { id: "u_1" },
headers: { "X-Request-Id": "request-123" },
});
自己提供 customFetch: typeof globalThis.fetch 用于代用、平台多填充、仪器或测试。 两者 createApiClient 财务报告和审定财务报表 new FetchExecutor({ fetch: customFetch }) 接受这一点。 没有它,执行者读 globalThis.fetch 在每次尝试。 选中的函数称为不绑定接收器 .
客户头可以是静态记录或同步/同步提供者. 供应商每次尝试运行一次,包括复试,然后由请求头覆盖。 虚数被省去. 提供方失败抛出消毒器 UnexpectedApiClientError 而不保留原始消息或原因。 见 核心 API 用于合并、重试和超时细节.