keq
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseKeq
Keq
TypeScript HTTP client built on Fetch API. Combines Koa-style middleware architecture with SuperAgent-style chainable API.
基于Fetch API构建的TypeScript HTTP客户端。结合了Koa风格的中间件架构与SuperAgent风格的链式API。
Installation
安装
bash
npm install keqAll and packages must use the same version number. Upgrade them together.
keq@keq-request/*bash
npm install keq所有和包必须使用相同的版本号,请一并升级它们。
keq@keq-request/*Import
导入
typescript
import { request } from "keq"requestKeqRequesttypescript
import { KeqRequest } from "keq"
const api = new KeqRequest({ baseOrigin: "https://api.example.com" })typescript
import { request } from "keq"requestKeqRequesttypescript
import { KeqRequest } from "keq"
const api = new KeqRequest({ baseOrigin: "https://api.example.com" })HTTP Methods
HTTP方法
typescript
await request.get(url)
await request.post(url)
await request.put(url)
await request.patch(url)
await request.delete(url)
await request.head(url)typescript
await request.get(url)
await request.post(url)
await request.put(url)
await request.patch(url)
await request.delete(url)
await request.head(url)Request Building
请求构建
typescript
await request
.post("/cats/{catId}")
.params("catId", "123") // URI template params (RFC 6570)
.query({ breed: "british" }) // Query string
.set("Authorization", "Bearer t") // Headers
.send({ name: "mimi", age: 3 }) // JSON bodyFor FormData:
typescript
await request
.post("/upload")
.field("name", "mimi")
.attach("avatar", blob)typescript
await request
.post("/cats/{catId}")
.params("catId", "123") // URI模板参数(RFC 6570)
.query({ breed: "british" }) // 查询字符串
.set("Authorization", "Bearer t") // 请求头
.send({ name: "mimi", age: 3 }) // JSON请求体FormData格式:
typescript
await request
.post("/upload")
.field("name", "mimi")
.attach("avatar", blob)Response Handling
响应处理
Default mode auto-parses by Content-Type (JSON → object, text → string).
typescript
const cat = await request.get<Cat>("/cats/1")Explicit serialization:
typescript
const data = await request
.get("/x")
.resolveWith("json")
const text = await request
.get("/x")
.resolveWith("text")
const res = await request
.get("/x")
.resolveWith("response")
const blob = await request
.get("/x")
.resolveWith("blob")SSE streaming:
typescript
const stream = await request
.get("/events")
.resolveWith("sse")
for await (const event of stream) {
console.log(event.event, event.data)
}默认模式会根据Content-Type自动解析(JSON→对象,文本→字符串)。
typescript
const cat = await request.get<Cat>("/cats/1")显式序列化:
typescript
const data = await request
.get("/x")
.resolveWith("json")
const text = await request
.get("/x")
.resolveWith("text")
const res = await request
.get("/x")
.resolveWith("response")
const blob = await request
.get("/x")
.resolveWith("blob")SSE流处理:
typescript
const stream = await request
.get("/events")
.resolveWith("sse")
for await (const event of stream) {
console.log(event.event, event.data)
}Timeout & Retry
超时与重试
typescript
import { request, TimeoutException } from "keq"
await request
.get("/data")
.timeout(5000)
await request
.get("/data")
.retry(3, 1000)
await request
.get("/data")
.retry(5, (attempt) => Math.pow(2, attempt - 1) * 1000)typescript
import { request, TimeoutException } from "keq"
await request
.get("/data")
.timeout(5000)
await request
.get("/data")
.retry(3, 1000)
await request
.get("/data")
.retry(5, (attempt) => Math.pow(2, attempt - 1) * 1000)Instance Management
实例管理
typescript
import { KeqRequest } from "keq"
const parent = new KeqRequest({ baseOrigin: "https://api.example.com" })
const child = parent.fork() // Inherits parent middleware
child.inherit(parent) // Or: parent.adopt(child)Parent-child relationship is live: middleware added to parent after / still applies to child.
fork()inherit()typescript
import { KeqRequest } from "keq"
const parent = new KeqRequest({ baseOrigin: "https://api.example.com" })
const child = parent.fork() // 继承父实例的中间件
child.inherit(parent) // 或者使用:parent.adopt(child)父子实例关系是动态的:在/之后添加到父实例的中间件仍然会作用于子实例。
fork()inherit()Middleware (Overview)
中间件(概述)
Koa-style onion model. Code before runs pre-request, after runs post-response.
await next()typescript
import { KeqMiddleware } from "keq"
const auth: KeqMiddleware = async (ctx, next) => {
ctx.request.headers.set("Authorization", "Bearer token")
await next()
}
request.use(auth)Route-scoped:
typescript
request
.apply(auth)
.forRoutes({ host: "api.example.com" })
request
.apply(logger)
.exclude({ pathname: "/health" })
.forAllRoutes()For complete middleware API (context object, data sharing, orchestration, module augmentation), consult .
references/middleware.mdKoa风格的洋葱模型。之前的代码在请求前执行,之后的代码在响应后执行。
await next()typescript
import { KeqMiddleware } from "keq"
const auth: KeqMiddleware = async (ctx, next) => {
ctx.request.headers.set("Authorization", "Bearer token")
await next()
}
request.use(auth)路由作用域:
typescript
request
.apply(auth)
.forRoutes({ host: "api.example.com" })
request
.apply(logger)
.exclude({ pathname: "/health" })
.forAllRoutes()如需完整的中间件API(上下文对象、数据共享、编排、模块扩展),请查阅****。
references/middleware.mdFlow Control (Overview)
流控制(概述)
Built-in concurrency management via :
.flowControl()| Strategy | Behavior |
|---|---|
| Queue, execute one at a time |
| Limit parallel to N |
| Cancel previous pending request |
| Reject new if one is pending |
typescript
await request
.get("/search")
.query("q", value)
.flowControl("abort", "search")
await request
.get("/items")
.flowControl("concurrent", 5, "batch")For detailed strategies, signals, and error handling, consult .
references/flow-control.md通过实现内置的并发管理:
.flowControl()| 策略 | 行为 |
|---|---|
| 队列模式,依次执行 |
| 限制最大并行数为N |
| 取消之前的待处理请求 |
| 若已有请求待处理,则拒绝新请求 |
typescript
await request
.get("/search")
.query("q", value)
.flowControl("abort", "search")
await request
.get("/items")
.flowControl("concurrent", 5, "batch")如需详细的策略、信号和错误处理说明,请查阅****。
references/flow-control.mdEvents
事件
typescript
await request
.get("/cats")
.retry(3)
.on("retry", ({ attempt }) => console.log(`Retry #${attempt}`))
.on("error", (err) => console.error(err))
.on("timeout", () => console.warn("Timed out"))typescript
await request
.get("/cats")
.retry(3)
.on("retry", ({ attempt }) => console.log(`第${attempt}次重试`))
.on("error", (err) => console.error(err))
.on("timeout", () => console.warn("请求超时"))Derive & Fire
派生与触发
typescript
const base = request
.get("/cats")
.set("Authorization", "Bearer t")
const [p1, p2] = await Promise.all([
base
.derive()
.query("page", 1),
base
.derive()
.query("page", 2),
])
request
.post("/analytics")
.send({ event: "view" })
.fire()typescript
const base = request
.get("/cats")
.set("Authorization", "Bearer t")
const [p1, p2] = await Promise.all([
base
.derive()
.query("page", 1),
base
.derive()
.query("page", 2),
])
request
.post("/analytics")
.send({ event: "view" })
.fire()Additional Resources
额外资源
For detailed API references beyond daily usage:
- — Full chainable API: query options, route params, body types, auth, credentials
references/request-building.md - — Context object, registration patterns, data sharing, module augmentation, orchestrator
references/middleware.md - — All strategies with signals, error handling, queue isolation
references/flow-control.md - — KeqApiSchema, generic typing, module declaration extensions
references/types.md
如需日常使用之外的详细API参考:
- — 完整链式API:查询选项、路由参数、请求体类型、身份验证、凭证
references/request-building.md - — 上下文对象、注册模式、数据共享、模块扩展、编排器
references/middleware.md - — 所有策略的信号、错误处理、队列隔离
references/flow-control.md - — KeqApiSchema、泛型类型、模块声明扩展
references/types.md