listpage-http
v0.0.320
Published
基于原生 fetch 的配置驱动 HTTP 客户端,用于统一处理 JSON 请求与 SSE 流(浏览器与 Node 18+)。
Readme
listpage-http
基于浏览器原生 fetch 的配置驱动 HTTP 客户端,用于统一处理 JSON 请求与 SSE 流。
核心能力
- 配置驱动:通过集中式
requestConfig描述所有接口(method / path / 默认超时 / 缓存 / 是否 SSE)。 - 类型安全:使用
defineEndpoint<Req, Res>()明确每个接口的请求 / 响应类型。 - 统一错误模型:约定后端返回
{ code, message, data },内部根据successCodes/unauthorizedCodes进行解析。 - 可选超时与缓存:仅在接口级或调用级显式配置时才启用超时 / 缓存逻辑。
- SSE 支持:基于
fetch+ReadableStream,统一由coreSseRequest封装建连与错误处理。
主要导出
- 类型:
ClientOptions,RequestOptionsEndpointConfig,EndpointMode,ApiEnvelope
- 配置工具:
defineEndpoint
- 客户端:
createApiClient,ApiClient
- Core 层:
coreRequest,coreSseRequest
- 缓存工具:
getCache,setCache,invalidateCache,invalidateByPrefix,buildDefaultCacheKey
- 错误类型:
ApiError,RequestTimeoutException
快速上手
- 定义 requestConfig:
import { defineEndpoint } from "listpage-http";
export const requestConfig = {
auth: {
login: defineEndpoint<{ username: string; password: string }, { token: string }>({
method: "POST",
path: "/auth/login",
authRequired: false,
defaultOptions: {
timeout: 10_000,
},
}),
},
} as const;- 初始化客户端:
import { createApiClient } from "listpage-http";
import { requestConfig } from "./request-config";
export const api = createApiClient(requestConfig, {
baseURL: import.meta.env.DEV ? "http://localhost:3000/api" : "/api",
tokenKey: "__REQUEST_TOKEN__",
defaultTimeout: 10_000,
defaultCacheTime: 5_000,
successCodes: [0],
unauthorizedCodes: [401, 403],
unauthorizedRedirectPath: "/login",
onError: (code, message) => {
console.error("API Error:", code, message);
},
});- 业务中调用:
const res = await api.auth.login(
{ username, password },
{
timeout: 5_000,
}
);- SSE 示例:
const stream = await api.agent.generateCode(
{ id },
{
timeout: 3_000, // 建连超时
}
);