@cendo91/fetch-protocol-kit
v0.1.9
Published
Framework-independent Fetch HTTP client with configurable response protocols
Readme
Fetch Protocol Kit
基于原生 Fetch 的通用 HTTP 客户端,支持声明式响应解包、自定义协议、动态请求头、表单、超时和取消。包使用 ESM,包含 TypeScript 类型,运行时零依赖。
Framework-independent Fetch client with configurable response protocols, dynamic headers, forms, timeouts and cancellation. ESM with TypeScript types and no runtime dependencies.
安装 / Installation
npm install @cendo91/fetch-protocol-kit基础请求 / Basic requests
不需要业务解包时只配置地址,默认返回完整解析体。
Configure the base URL to return the full parsed response without business decoding.
import { createHttpClient } from "@cendo91/fetch-protocol-kit";
const http = createHttpClient({ baseUrl: "https://api.example.com" });
const users = await http.get<{ id: string }[]>("/users", { page: 1 });
await http.post("/users", { name: "Alice" });严格 JSON 解析 / Strict JSON parsing
启用 strictJson: true 后,成功的 JSON 响应若为空或无法解析,会抛出保留 HTTP 状态的 INVALID_RESPONSE。204 仍返回 null,非 2xx 响应继续由 HTTP 错误处理提取状态码和错误体。此选项默认关闭,单次请求可覆盖客户端配置。
Enable strictJson: true to reject empty or malformed successful JSON responses with INVALID_RESPONSE and the HTTP status. A 204 still returns null, and HTTP error handling keeps the status and error payload. The option defaults to off and can be overridden per request.
import { createHttpClient } from "@cendo91/fetch-protocol-kit";
const http = createHttpClient({ baseUrl: "https://api.example.com", strictJson: true });
await http.get("/users");
await http.get("/legacy", undefined, { strictJson: false });
await http.get("/health.txt", undefined, { responseType: "text" });声明式响应 / Declarative responses
对于 { code: 0, data: ..., message: "ok" } 这类顶层包装,启用 response 后校验业务状态并返回 data。字段名与成功值均可配置。
For a top-level { code: 0, data: ..., message: "ok" } envelope, enable response to validate success and return data. Field names and success values are configurable.
import { createHttpClient } from "@cendo91/fetch-protocol-kit";
const http = createHttpClient({ baseUrl: "https://api.example.com", response: {} });
const users = await http.get<{ id: string }[]>("/users");
await http.patchForm("/users/1", { name: "Alice" });response: {} 默认采用code=0/data/message规则,业务失败抛出ApiError。单次 responseMode: "envelope" 在成功校验后保留完整包装;response: false 只跳过声明式规则。
response: {} defaults to code=0/data/message and throws ApiError on business failure. Per-request responseMode: "envelope" returns the validated full envelope; response: false skips declarative decoding only.
自定义协议 / Custom protocols
decodeResponse 处理成功的 HTTP 响应,createHttpError 映射非 2xx 响应。自定义回调和声明式 response 需择一配置。
decodeResponse handles successful HTTP responses and createHttpError maps non-2xx responses. Choose custom hooks or the declarative response configuration.
import { ApiError, createHttpClient, type ResponseContext } from "@cendo91/fetch-protocol-kit";
type Envelope = { status?: { code?: unknown; message?: unknown }; result?: unknown };
function protocolError(body: unknown, { response, url }: ResponseContext) {
const status = (body as Envelope | null)?.status;
return new ApiError(
typeof status?.message === "string" ? status.message : "Request failed",
{ code: typeof status?.code === "string" ? status.code : undefined,
status: response.status, url, data: body },
);
}
const http = createHttpClient({
baseUrl: "https://api.example.com",
createHttpError: protocolError,
decodeResponse(body, context) {
if (context.response.status === 204) return null;
const envelope = body as Envelope | null;
const code = envelope?.status?.code;
if (typeof code === "string" && code !== "OK") throw protocolError(body, context);
if (code !== "OK" || !envelope || !Object.prototype.hasOwnProperty.call(envelope, "result")) {
throw new ApiError("Invalid response", {
code: "INVALID_RESPONSE", status: context.response.status, data: body, url: context.url,
});
}
return envelope.result;
},
});
const user = await http.get<{ id: string }>("/users/1");超时配置工具 / Timeout configuration helper
import { createHttpClient, parseTimeout } from "@cendo91/fetch-protocol-kit";
const timeoutSetting: string | undefined = "5000";
const http = createHttpClient({
baseUrl: "https://api.example.com",
timeout: parseTimeout(timeoutSetting),
});parseTimeout(value, fallback = 15000) 接收字符串、数字或undefined,返回有限非负数;缺省、负值、NaN和Infinity使用兜底值。沿用Number转换:空字符串/纯空白转为0,0关闭超时;自定义fallback由调用方保证为有限非负数。工具不读取环境变量,createHttpClient继续严格接收数字。
parseTimeout converts string/number/undefined input using Number. Missing, negative or non-finite input uses the fallback (15000 ms by default). Empty/whitespace strings become 0 and disable timeouts. Supply a finite, non-negative fallback. The helper does not read environment variables; client configuration still requires numeric timeouts.
超时覆盖动态请求头、传输和读取响应体。通过 signal 主动取消时,请求会及时结束等待。
The timeout covers dynamic headers, transport and reading the response body. A caller-provided signal stops waiting when aborted.
错误分类 / Error categories
公共包生成的 ApiError 带有 kind,可区分 timeout、aborted、http、business 等错误来源。code 保留既有错误码及后端业务码。完整分类见 API 参考。
Package-generated ApiError values expose kind for the error category and retain the original code. See the API reference for the complete list.
请求观察 / Request observation
可选的 onEvent 会收到请求、响应和错误的独立日志快照。错误快照包含最终抛出错误的分类与错误码。若已收到响应头但读取响应体失败,错误中保留 HTTP 状态。应用可以在输出前原地脱敏,实际发送和返回的数据保持原样。
The optional onEvent hook receives detached request, response, and error snapshots. Error snapshots carry the same category and code as the thrown error. A response body read failure retains the HTTP status once headers have arrived. Applications can redact snapshots in place before logging them.
可选的 shouldObserve({ type, debug }) 在创建快照前判断是否投递事件。返回 false 会跳过当前快照和 onEvent 调用。
The optional shouldObserve({ type, debug }) hook filters events before snapshots are created. Return false to skip both the snapshot and the onEvent call.
import { createHttpClient, createHttpLogger } from "@cendo91/fetch-protocol-kit";
const http = createHttpClient({
baseUrl: "https://api.example.com",
debug: true,
shouldObserve: ({ debug }) => debug,
onEvent: createHttpLogger(),
});
await http.get("/users");
await http.get("/health", undefined, { debug: false }); // Client debug is enabled.客户端的 debug 为 true 时,所有请求的调试标记都为 true。客户端传 false 或省略时,只有单次请求的 debug: true 才会开启。配合示例中的筛选,同一次调用产生的全部 req、res 和 err 事件都使用最终的 debug 值。
Set the client-level debug to true to enable debugging for every request. When it is false or omitted, a request opts in with debug: true. The filter above uses the resolved flag for every event the request produces.
createHttpLogger() 在每次请求结束时输出一个可折叠分组,展开后按行显示可用的请求方法、请求时间、响应时间、HTTP 状态码和总耗时。默认只输出日志元数据。
传入 createHttpLogger({ write: entry => buffer.push(entry) }) 可将结构化摘要写入应用自己的缓冲区。可用 selectDetails 从各事件选取已脱敏的 URL、请求头、请求体、响应体和错误详情。应用可调用 printHttpLog(entry) 用同样的样式显示缓冲中的日志。
createHttpLogger() writes one collapsible group after each observed request settles. Open a group to see request start, response arrival, HTTP status, and elapsed time on separate lines. Default output contains only event metadata. Pass { write } to send grouped entries to another destination and use selectDetails to include redacted details. Call printHttpLog(entry) to render buffered entries in the same style.
环境要求 / Requirements
支持 Node.js 20.9 及以上版本,或提供 Fetch、Headers、URL 和 AbortController 的浏览器。
Requires Node.js 20.9 or later, or a browser with Fetch, Headers, URL and AbortController.
