BBackOne Docsserver · utils · cli
Bun-nativeGitHub ↗
@geektech/backone

上下文与响应

Context API:params / query / body / cookie,响应构建与返回值序列化。

Context 是单个请求的处理上下文:query / body 采用惰性解析(首次访问时解析并缓存),避免热路径上的无谓开销;headers 与 state 用于在中间件与处理器之间传递响应头与共享数据。

读取请求

成员说明
request原始 Request 对象
method请求方法(大写)
pathname规范化后的路径名(不含 query)
params路径参数(由路由匹配写入,带类型泛型)
queryURLSearchParams,惰性解析并缓存
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 / null204(或 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')); // 302

HttpError

抛出 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。