okfetch
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineseokfetch
okfetch
Use this skill when the user wants to build HTTP clients or requests with the okfetch library.
当用户想要使用okfetch库构建HTTP客户端或请求时,可使用本技能。
Package selection
包选择指南
Choose the package based on the job:
- Use for direct typed requests with validation, retries, plugins, auth, timeouts, and streaming.
@okfetch/fetch - Use when the user wants a typed client generated from endpoint definitions.
@okfetch/api - Use when the user wants ready-made request logging through a plugin.
@okfetch/logger
If the user has repeated endpoint calls, shared request shapes, or wants one typed client object, prefer .
@okfetch/apiIf the user just needs a few requests or wants fine-grained transport control, prefer .
@okfetch/fetch根据需求选择对应的包:
- 若需要直接发送带类型校验、重试、插件、认证、超时和流处理的请求,请使用。
@okfetch/fetch - 若用户希望根据端点定义生成带类型的客户端,请使用。
@okfetch/api - 若用户需要通过插件实现现成的请求日志功能,请使用。
@okfetch/logger
如果用户需要重复调用端点、共享请求结构,或想要一个统一的带类型客户端对象,优先选择。
@okfetch/api如果用户只需要发送少量请求,或希望对传输层进行细粒度控制,优先选择。
@okfetch/fetchCore mental model
核心设计理念
okfetch stays close to the web platform. It makes safer and more composable without hiding how HTTP requests work.
fetchThe main usage pattern is:
- Define Zod schemas for request or response shapes.
- Call directly or generate a client with
okfetch(...).createApi(...) - Handle the returned explicitly instead of relying on thrown request errors.
Result
okfetch贴近Web平台设计,它让更安全、更具组合性,同时不会掩盖HTTP请求的工作原理。
fetch主要使用模式如下:
- 为请求或响应结构定义Zod Schema。
- 直接调用,或使用
okfetch(...)生成客户端。createApi(...) - 显式处理返回的对象,而非依赖抛出的请求错误。
Result
Result handling
Result处理
Request calls return a , not thrown transport or validation errors for expected failures.
ResultPrefer examples and implementations that use:
.match(...)- /
.isOk().isErr() - other helpers already available to the user
better-result
Do not default to for normal HTTP failure handling.
try/catch请求调用会返回对象,对于预期的失败场景,不会抛出传输或校验错误。
Result推荐使用以下方式处理:
.match(...)- /
.isOk().isErr() - 用户已有的其他工具函数
better-result
不要默认使用处理常规HTTP失败场景。
try/catch@okfetch/fetch
@okfetch/fetch@okfetch/fetch
@okfetch/fetchUse for direct requests.
okfetch(url, options)Common options:
- to validate successful responses
outputSchema - to validate structured error payloads
apiErrorDataSchema - and
paramsto build request URLsquery - for JSON request payloads
body - for basic, bearer, or custom authorization headers
auth - for
retry,fixed, orlinearretriesexponential - for request timeouts
timeout - for lifecycle extensions
plugins - for SSE-style streaming
stream: true
Prefer this shape in examples:
ts
import { okfetch } from "@okfetch/fetch";
import { z } from "zod/v4";
const userSchema = z.object({
id: z.number(),
name: z.string(),
});
const result = await okfetch("https://api.example.com/users/1", {
outputSchema: userSchema,
});
result.match({
err: (error) => {
console.error(error._tag, error.message);
},
ok: (user) => {
console.log(user.name);
},
});When showing error validation, use or from .
validateClientErrorsvalidateAllErrors@okfetch/fetchError tags to mention when relevant:
FetchErrorTimeoutErrorApiErrorParseErrorValidationErrorPluginError
Validation boundaries to keep straight:
- validates successful responses
outputSchema - validates structured error bodies
apiErrorDataSchema - applies validation to
validateClientErrorsresponses4xx - applies validation to
validateAllErrorsand4xxresponses5xx
使用发送直接请求。
okfetch(url, options)常用配置项:
- :校验成功响应的结构
outputSchema - :校验结构化错误载荷
apiErrorDataSchema - 和
params:构建请求URLquery - :JSON请求体
body - :基础认证、Bearer认证或自定义认证头
auth - :固定间隔、线性或指数退避重试
retry - :请求超时时间
timeout - :生命周期扩展插件
plugins - :启用SSE风格的流处理
stream: true
示例推荐使用如下结构:
ts
import { okfetch } from "@okfetch/fetch";
import { z } from "zod/v4";
const userSchema = z.object({
id: z.number(),
name: z.string(),
});
const result = await okfetch("https://api.example.com/users/1", {
outputSchema: userSchema,
});
result.match({
err: (error) => {
console.error(error._tag, error.message);
},
ok: (user) => {
console.log(user.name);
},
});展示错误校验时,请使用中的或。
@okfetch/fetchvalidateClientErrorsvalidateAllErrors相关场景下可提及以下错误标签:
FetchErrorTimeoutErrorApiErrorParseErrorValidationErrorPluginError
需明确以下校验边界:
- 校验成功响应
outputSchema - 校验结构化错误体
apiErrorDataSchema - 对
validateClientErrors响应应用校验4xx - 对
validateAllErrors和4xx响应应用校验5xx
@okfetch/api
@okfetch/api@okfetch/api
@okfetch/apiUse plus when the user wants a typed client from endpoint definitions.
createEndpoints(...)createApi(...)Endpoint definitions may include:
methodpathbodyparamsqueryoutputerrorrequestOptionsstream
This package validates , , and before sending the request, then delegates transport behavior to .
bodyparamsquery@okfetch/fetchPrefer this shape in examples:
ts
import { createApi, createEndpoints } from "@okfetch/api";
import { z } from "zod/v4";
const todoSchema = z.object({
id: z.number(),
title: z.string(),
completed: z.boolean(),
});
const endpoints = createEndpoints({
todos: {
get: {
method: "GET",
output: todoSchema,
params: z.object({ id: z.number() }),
path: "/todos/:id",
},
},
});
const api = createApi({
baseURL: "https://api.example.com",
endpoints,
});
const result = await api.todos.get({ params: { id: 1 } });Use when the user wants a class wrapper around a generated client.
ApiServicets
import { ApiService, createEndpoints } from "@okfetch/api";
import { z } from "zod/v4";
const todoSchema = z.object({
id: z.number(),
title: z.string(),
completed: z.boolean(),
});
const endpoints = createEndpoints({
todos: {
getById: {
method: "GET",
output: todoSchema,
params: z.object({ id: z.number() }),
path: "/todos/:id",
},
},
});
class TodoService extends ApiService(endpoints) {
constructor() {
super({
baseURL: "https://api.example.com",
});
}
getById(id: number) {
return this.client.todos.getById({
params: { id },
});
}
}
const todoService = new TodoService();
const result = await todoService.getById(1);Important behavior:
- global options act as shared transport defaults
createApi(...) - per-endpoint refine behavior for one endpoint
requestOptions - per-call overrides win over endpoint-level and global defaults
- response parsing, retries, auth, plugins, timeouts, and streaming still come from
@okfetch/fetch
当用户希望根据端点定义生成带类型的客户端时,使用搭配。
createEndpoints(...)createApi(...)端点定义可包含以下内容:
methodpathbodyparamsqueryoutputerrorrequestOptionsstream
该包会在发送请求前校验、和,然后将传输行为委托给。
bodyparamsquery@okfetch/fetch示例推荐使用如下结构:
ts
import { createApi, createEndpoints } from "@okfetch/api";
import { z } from "zod/v4";
const todoSchema = z.object({
id: z.number(),
title: z.string(),
completed: z.boolean(),
});
const endpoints = createEndpoints({
todos: {
get: {
method: "GET",
output: todoSchema,
params: z.object({ id: z.number() }),
path: "/todos/:id",
},
},
});
const api = createApi({
baseURL: "https://api.example.com",
endpoints,
});
const result = await api.todos.get({ params: { id: 1 } });当用户需要为生成的客户端添加类包装时,使用。
ApiServicets
import { ApiService, createEndpoints } from "@okfetch/api";
import { z } from "zod/v4";
const todoSchema = z.object({
id: z.number(),
title: z.string(),
completed: z.boolean(),
});
const endpoints = createEndpoints({
todos: {
getById: {
method: "GET",
output: todoSchema,
params: z.object({ id: z.number() }),
path: "/todos/:id",
},
},
});
class TodoService extends ApiService(endpoints) {
constructor() {
super({
baseURL: "https://api.example.com",
});
}
getById(id: number) {
return this.client.todos.getById({
params: { id },
});
}
}
const todoService = new TodoService();
const result = await todoService.getById(1);重要行为说明:
- 全局配置项作为共享的传输层默认设置
createApi(...) - 单个端点的可覆盖该端点的默认行为
requestOptions - 单次调用的配置优先级高于端点级和全局默认配置
- 响应解析、重试、认证、插件、超时和流处理仍由提供支持
@okfetch/fetch
@okfetch/logger
@okfetch/logger@okfetch/logger
@okfetch/loggerUse from as a plugin for request lifecycle logging.
logger()@okfetch/loggerPrefer this shape in examples:
ts
import { okfetch } from "@okfetch/fetch";
import { logger } from "@okfetch/logger";
await okfetch("https://api.example.com/health", {
plugins: [logger()],
});When useful, mention as the main option for including parsed success payloads in logs.
logDataOnSuccessThe logger plugin covers these lifecycle moments:
- request start
- success
- failure
- retry
使用中的作为插件,实现请求生命周期日志记录。
@okfetch/loggerlogger()示例推荐使用如下结构:
ts
import { okfetch } from "@okfetch/fetch";
import { logger } from "@okfetch/logger";
await okfetch("https://api.example.com/health", {
plugins: [logger()],
});必要时可提及配置项,它是在日志中包含解析后的成功响应数据的主要选项。
logDataOnSuccess日志插件覆盖以下生命周期节点:
- 请求开始
- 请求成功
- 请求失败
- 请求重试
Streaming
流处理
When the user asks about streaming or server-sent events:
- use
stream: true - explain that each SSE chunk is parsed independently
data: - if is present, explain that each chunk is validated before emission
outputSchema
当用户询问流处理或服务器发送事件(SSE)相关内容时:
- 启用配置
stream: true - 说明每个SSE的块会被独立解析
data: - 如果配置了,说明每个块在输出前都会被校验
outputSchema
Guidance for answers
回答指导
- Keep examples TypeScript-first.
- Use in examples.
zod/v4 - Prefer consumer-facing code snippets over repository implementation details.
- Keep the distinction between transport concerns and endpoint-definition concerns clear.
- If a user asks which package to use, answer with a recommendation, not a neutral dump of all APIs.
- 示例优先使用TypeScript编写。
- 示例中使用。
zod/v4 - 优先展示面向开发者的代码片段,而非仓库实现细节。
- 明确区分传输层相关关注点和端点定义相关关注点。
- 如果用户询问应使用哪个包,请给出明确推荐,而非中立地罗列所有API。