跳转到内容

Auto Bind

bindJSONbindFormbindQuery 提供了从请求中自动解析、类型转换和 Schema 校验的一体化方案。

import { bindJSON } from "@ventostack/core";
const schema = {
name: { type: "string", required: true, min: 1, max: 50 },
email: { type: "string", required: true },
age: { type: "number", min: 0 },
};
app.post("/users", async (ctx) => {
const { data, errors } = await bindJSON(ctx, schema);
if (errors.length) {
return ctx.json({ errors }, 400);
}
return ctx.json(data);
});

application/x-www-form-urlencoded 解析,自动根据 Schema 做类型转换:

import { bindForm } from "@ventostack/core";
app.post("/login", async (ctx) => {
const { data, errors } = await bindForm(ctx, {
username: { type: "string", required: true },
remember: { type: "boolean" }, // "true"/"1" → true
});
if (errors.length) return ctx.json({ errors }, 400);
return ctx.json(data);
});

同步操作,从 URL 查询参数解析:

import { bindQuery } from "@ventostack/core";
app.get("/search", (ctx) => {
const { data, errors } = bindQuery(ctx, {
q: { type: "string", required: true },
page: { type: "number", min: 1 }, // "1" → 1
});
if (errors.length) return ctx.json({ errors }, 400);
return ctx.json({ query: data });
});

bindJSONbindForm 内置以下安全检查:

检查项默认值
Content-Type 校验必须匹配
最大 Body 大小1 MB
最大嵌套深度(仅 JSON)10 层
属性类型默认值说明
maxBodySizenumber1048576(1MB)最大 Body 大小(字节)
maxDepthnumber10JSON 最大嵌套深度
属性类型说明
dataT解析后的数据
errorsstring[]校验错误列表,空数组表示通过