keq

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Keq

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 keq
All
keq
and
@keq-request/*
packages must use the same version number. Upgrade them together.
bash
npm install keq
所有
keq
和
@keq-request/*
包必须使用相同的版本号,请一并升级它们。

Import

导入

typescript
import { request } from "keq"
request
is a singleton
KeqRequest
instance. For isolated instances:
typescript
import { KeqRequest } from "keq"

const api = new KeqRequest({ baseOrigin: "https://api.example.com" })
typescript
import { request } from "keq"
request
是一个单例
KeqRequest
实例。如需独立实例:
typescript
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 body
For 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
fork()
/
inherit()
still applies to child.
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
await next()
runs pre-request, after runs post-response.
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.md
.
Koa风格的洋葱模型。
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.md
**。

Flow Control (Overview)

流控制(概述)

Built-in concurrency management via
.flowControl()
:
StrategyBehavior
serial
Queue, execute one at a time
concurrent
Limit parallel to N
abort
Cancel previous pending request
mutex
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()
实现内置的并发管理:
策略行为
serial
队列模式,依次执行
concurrent
限制最大并行数为N
abort
取消之前的待处理请求
mutex
若已有请求待处理,则拒绝新请求
typescript
await request
  .get("/search")
  .query("q", value)
  .flowControl("abort", "search")
await request
  .get("/items")
  .flowControl("concurrent", 5, "batch")
如需详细的策略、信号和错误处理说明,请查阅**
references/flow-control.md
**。

Events

事件

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:
  • references/request-building.md
    — Full chainable API: query options, route params, body types, auth, credentials
  • references/middleware.md
    — Context object, registration patterns, data sharing, module augmentation, orchestrator
  • references/flow-control.md
    — All strategies with signals, error handling, queue isolation
  • references/types.md
    — KeqApiSchema, generic typing, module declaration extensions
如需日常使用之外的详细API参考:
  • references/request-building.md
    — 完整链式API:查询选项、路由参数、请求体类型、身份验证、凭证
  • references/middleware.md
    — 上下文对象、注册模式、数据共享、模块扩展、编排器
  • references/flow-control.md
    — 所有策略的信号、错误处理、队列隔离
  • references/types.md
    — KeqApiSchema、泛型类型、模块声明扩展