@geektech/backone
上下文与响应
Context API:params / query / body / cookie,响应构建与返回值序列化。
Context 是单个请求的处理上下文:query / body 采用惰性解析(首次访问时解析并缓存),避免热路径上的无谓开销;headers 与 state 用于在中间件与处理器之间传递响应头与共享数据。
读取请求
| 成员 | 说明 |
|---|---|
request | 原始 Request 对象 |
method | 请求方法(大写) |
pathname | 规范化后的路径名(不含 query) |
params | 路径参数(由路由匹配写入,带类型泛型) |
query | URLSearchParams,惰性解析并缓存 |
headers | 响应头构建器 |
state | 中间件与处理器之间共享的可变数据 |
ts
app.get<{ id: string }>('/users/:id', (ctx) => {
const id = ctx.params.id;
const page = ctx.query.get('page') ?? '1';
const token = ctx.getHeader('authorization');
ctx.state.visited = true;
return { id, page };
});请求体
三种惰性解析方式,解析失败抛出 HttpError(400):
| 方法 | 说明 |
|---|---|
bodyJson<T>() | 解析 JSON 请求体并返回类型化对象;非法 JSON 抛 400 |
bodyText() | 读取文本请求体 |
bodyForm() | 解析表单(multipart/form-data 或 urlencoded),返回标准 FormData 方法子集 |
ts
app.post('/users', async (ctx) => {
const body = await ctx.bodyJson<{ name: string; email: string }>();
return ctx.json({ created: true, name: body.name }, 201);
});Cookie
ts
// 读取请求 Cookie
const theme = ctx.cookie('theme');
// 追加响应 Set-Cookie(链式)
ctx.setCookie('theme', 'dark', {
httpOnly: true,
sameSite: 'Lax',
maxAge: 60 * 60 * 24 * 7,
path: "/",
});构建响应
| 方法 | 说明 |
|---|---|
json(data, status?) | JSON 响应(默认 application/json) |
text(data, status?) | 纯文本响应 |
html(data, status?) | HTML 响应 |
stream(body, status?) | 流式响应 |
redirect(url, status=302) | 重定向 |
noContent() | 204 No Content |
set(name, value) | 设置响应头(链式) |
status | 读写响应状态码,默认 200 |
返回值序列化
处理器可以不显式构建 Response,直接返回值,由框架统一序列化:
| 返回值 | 行为 |
|---|---|
| Response | 直接透传(零开销) |
| string | 按文本响应 |
| number / boolean | 按文本响应 |
| object | 按 JSON 响应 |
| undefined / null | 204(或 ctx.status) |
ts
app.get('/a', () => 'text'); // text/plain
app.get('/b', () => ({ ok: true })); // application/json
app.get('/c', () => undefined); // 204
app.get('/d', (ctx) => ctx.redirect('/login')); // 302HttpError
抛出 HttpError 即可由框架统一转为 JSON 错误响应(development 模式下 5xx 会输出错误详情与 cause):
ts
import { HttpError } from '@geektech/backone';
if (!user) throw new HttpError(404, 'User not found');
if (!allowed) throw new HttpError(403);响应体格式:{"error": "<message>", "status": <code>};非 development 模式下的 5xx 统一返回 Internal Server Error 避免泄漏细节。
继续:WebSocket。