用 @eggjs/typebox-validate 在 Egg + TypeScript 中实现“写一遍类型“的参数校验

发布时间:2026/9/21 16:14:08
用 @eggjs/typebox-validate 在 Egg + TypeScript 中实现“写一遍类型“的参数校验 用 eggjs/typebox-validate 在 Egg TypeScript 中实现写一遍类型的参数校验【免费下载链接】egg Born to build better enterprise frameworks and apps with Node.js Koa. https://307.run/eggcode项目地址: https://gitcode.com/gh_mirrors/eg/egg导读在 Egg 与 TypeScript 项目中ctx.validate的参数校验长期存在同一份参数要写两遍定义的痛点一遍是给运行时的 JS 校验规则parameter 库的字符串写法另一遍是给编译期的 TS 类型定义。本文围绕eggjs/typebox-validate插件展开讲解如何用 TypeBox 的 JSON Schema 描述一次参数结构同时获得运行时校验能力与静态类型推导并深入插件源码说明ctx.tValidate、Validate装饰器、AJV 实例初始化与自定义 format 的底层实现帮助你低成本从 egg-validate 渐进迁移。为什么需要一个新的校验方案在 TypeScript 的 Egg 项目里传统写法通常长这样class HomeController extends Controller { async index() { const { ctx } this; // 写一遍 js 的类型校验 ctx.validate({ id: string, name: { type: string, required: false, }, timestamp: { type: number, required: false, }, }, ctx.params); // 写一遍 ts 的类型定义为了后面拿参数定义 const params: { id: string; name?: string; timestamp: number; } ctx.params; ... ctx.body params.id; } } export default HomeController;可以看到这里同一份参数写了两遍定义一遍用 parameter 库的 JS 规则另一遍用 TS 类型做强转目的是让后续代码获得类型提示。简单类型尚可接受一旦参数结构复杂多层嵌套、枚举、交叉类型、条件字段双份维护的成本和出错概率都会显著上升——尤其是 parameter 的字符串写法如nunber容易手误复杂嵌套对象的规则写法每次都要翻文档。eggjs/typebox-validate的核心思路是用 TypeBox 描述一次同时获得运行时校验 编译期类型这就是write once。 import { Static, Type } from eggjs/typebox-validate/typebox; class HomeController extends Controller { async index() { const { ctx } this; - ctx.validate({ - id: string, - name: { - type: string, - required: false, - }, - timestamp: { - type: number, - required: false, - }, - }, ctx.params); const paramsSchema Type.Object({ id: Type.String(), name: Type.Optional(Type.String()), timestamp: Type.Optional(Type.Integer()), }); ctx.tValidate(paramsSchema, ctx.params); const params: Statictypeof paramsSchema ctx.params; - const params: { - id: string; - name?: string; - timestamp: number; - } ctx.params; ... ctx.body params.id; } } export default HomeController;Statictypeof paramsSchema会自动推导出对应的 TS 类型id: string; name?: string; timestamp?: number不再需要手写第二遍类型。快速上手1. 安装npm i eggjs/typebox-validate注意该插件面向 Egg 的 TypeScript 项目当前仓库基于egg的next分支演进package.json中engines.node 22.18.0。若你使用的是egg3.xREADME 指出应使用社区维护的egg-typebox-validate版本。2. 在项目中启用插件在config/plugin.ts中注册// config/plugin.ts import typeboxValidatePlugin from eggjs/typebox-validate; export default { ...typeboxValidatePlugin(), };插件本身通过definePluginFactory注册见 src/index.tsname 为typeboxValidate默认enable: true。安装后ctx.tValidate/ctx.tValidateWithoutThrow即被挂载到 Context 上app.ajv挂载到 Application 上。3. 在业务代码中使用官方推荐把 schema 定义在 controller 外部模块级静态常量这样 AJV 可以编译一次、反复复用性能最佳 import { Static, Type } from eggjs/typebox-validate/typebox; // 写在 controller 外面静态化性能更好 const paramsSchema Type.Object({ id: Type.String(), name: Type.String(), timestamp: Type.Integer(), }); // 可以直接 export 出去给下游 service 使用 export type ParamsType Statictypeof paramsSchema; class HomeController extends Controller { async index() { const { ctx } this; // 直接校验 ctx.tValidate(paramsSchema, ctx.params); // 不用写 js 类型定义 const params: ParamsType ctx.params; ... } } export default HomeController;eggjs/typebox-validate/typebox子路径只是对typebox包的重导出见 src/typebox.ts因此你可以直接使用 TypeBox 的全部类型构造器。除了 write once还有更多好处1. 类型组合天然解决 DRYTypeBox 的 schema 是普通对象可以像积木一样组合。比如多张 DB 表都包含name 必填 description 选填的公共字段就可以抽出一个公共 schemaexport const TYPEBOX_NAME_DESC_OBJECT Type.Object({ name: Type.String(), description: Type.Optional(Type.String()), }); // type NameAndDesc { name: string; description?: string } type NameAndDesc Statictypeof TYPEBOX_NAME_DESC_OBJECT; // controller User async create() { const { ctx } this; const USER_TYPEBOX Type.Intersect([ TYPEBOX_NAME_DESC_OBJECT, Type.Object({ avatar: Type.String() }), ]); ctx.tValidate(USER_TYPEBOX, ctx.request.body); // 编辑器里正确得到提示 // type User { name: string; description?: string } { avatar: string } const { name, description, avatar } ctx.request.body as Statictypeof USER_TYPEBOX; ... } // controller Photo async create() { const { ctx } this; const PHOTO_TYPEBOX Type.Intersect([ TYPEBOX_NAME_DESC_OBJECT, Type.Object({ location: Type.String() }), ]); ctx.tValidate(PHOTO_TYPEBOX, ctx.request.body); // type Photo { name: string; description?: string } { location: string } const { name, description, location } ctx.request.body as Statictypeof PHOTO_TYPEBOX; ... }Type.Intersect组合出的运行时 schema 与推导出的 TS 类型保持严格一致公共字段只需维护一处。2. 校验规范是业界标准的 JSON Schema校验规则遵循 JSON Schema 规范插件在初始化 AJV 时通过ajv-formats注册了一批开箱即用的 format见 src/app.tsdate-time, time, date, email, hostname, ipv4, ipv6, uri, uri-reference, uuid, uri-template, json-pointer, relative-json-pointer, regex也就是说Type.String({ format: email })、Type.String({ format: date-time })这类写法开箱即用无需额外配置。除了 formatminLength、maxLength、minimum、pattern等 JSON Schema 关键字也都原生支持。3. 有类型提示、语法更不容易写错TypeBox 的写法是Type.Number()、Type.Optional(Type.String())这种带类型提示的链式 API编辑器会即时给出可用的构造器与参数相比 parameter 的字符串写法string、number全凭记忆写错只在运行时暴露TypeBox 在写的时候就能发现错误复杂嵌套对象的可读性也更好。与 egg-validate 的性能对比插件底层使用 AJVAjv2019实现AJV 的核心优势是把 schema 编译成校验函数当 schema 被定义在模块级静态化时编译只发生一次后续每次校验都直接执行编译后的函数。仓库提供了 benchmark 脚本 benchmark/ajv-vs-parameter.mjsREADME 中简写为./benchmark/ajv-vs-parameter.mjs对比了四种场景suite .add(#ajv, function () { const rule Type.Object({ name: Type.String(), description: Type.Optional(Type.String()), location: Type.Enum({ shanghai: shanghai, hangzhou: hangzhou }), }); ajv.validate(rule, DATA); }) .add(#ajv define once, function () { ajv.validate(typeboxRule, DATA); }) .add(#parameter, function () { const rule { name: string, description: { type: string, required: false, }, location: [shanghai, hangzhou], }; p.validate(rule, DATA); }) .add(#parameter define once, function () { p.validate(parameterRule, DATA); });在 MacBook Pro2.2 GHz 六核 Intel Core i7上的结果#ajv x 941 ops/sec ±3.97% (73 runs sampled) #ajv define once x 17,188,370 ops/sec ±11.53% (73 runs sampled) #parameter x 2,544,118 ops/sec ±4.36% (79 runs sampled) #parameter define once x 2,541,590 ops/sec ±5.34% (77 runs sampled) Fastest is #ajv define once结论很明确把 schema 静态化define once后AJV 的吞吐量比 parameter 高出一个数量级以上。这也正是官方强烈建议把 schema 定义在模块级的原因。需要说明的是这些数字来自项目作者在其硬件环境下的 benchmark 结果具体性能仍应以你自己的运行环境实测为准。从 egg-validate 迁移的成本迁移路径非常清晰只有三步把原来字符串式 JS 对象规则迁移为 TypeBox 对象写法string→Type.String()required: false→Type.Optional(...)把ctx.validate替换为ctx.tValidate或按需使用ctx.tValidateWithoutThrow建议渐进式迁移先迁简单、对业务影响小的接口再逐步覆盖复杂接口避免一次性大规模改动引入回归风险。API 详解插件在egg的 Context 上扩展了两个方法在 Application 上扩展了一个ajv属性类型声明见 src/app/extend/context.ts 与 src/app.ts。1.ctx.tValidate(schema, data)校验失败后抛出异常错误码与错误结构刻意与ctx.validate保持一致HTTP 422code: invalid_paramimport { Static, Type } from eggjs/typebox-validate/typebox; ctx.tValidate(Type.Object({ name: Type.String(), }), ctx.request.body);底层实现src/app/extend/context.tstValidate(schema: Schema, data: unknown): boolean { const ajv this.app.ajv; const res ajv.validate(schema, data); if (!res) { this.throw(422, Validation Failed, { code: invalid_param, errorData: data, currentSchema: JSON.stringify(schema), errors: ajv.errors, }); } return res; }失败时抛出的错误对象携带errorsAJV 的ErrorObject[]、errorData本次校验的数据和currentSchema序列化后的 schema方便排查与统一错误处理。2.ctx.tValidateWithoutThrow(schema, data)只做校验、不抛异常返回布尔值适合需要自行处理错误的场景import { Static, Type } from eggjs/typebox-validate/typebox; const valid ctx.tValidateWithoutThrow(Type.Object({ name: Type.String(), }), ctx.request.body); if (valid) { ... } else { const errors this.app.ajv.errors; // handle errors ... }注意校验结果仍存放在app.ajv.errors上可在else分支中读取。测试用例test/index.test.ts中update接口正是用这种方式手动返回 422 与errors的。3. 装饰器Validate推荐装饰器写法更干净把取数据 校验 失败处理全部声明式化import { Validate, ValidateFactory } from eggjs/typebox-validate/decorator; const ValidateWithRedirect ValidateFactory(ctx ctx.redirect(/422)); class HomeController extends Controller { Validate([ [paramsSchema, ctx ctx.params], [bodySchema, ctx ctx.request.body, (ctx, errors) MyErrorPrefix: errors.map(e e.message).join(, )], ]) async index() { const { ctx } this; // 直接校验 // 不用写 js 类型定义 const params: ParamsType ctx.params; ... } ValidateWithRedirect([paramsSchema, ctx ctx.params]) async post() { // ... } } export default HomeController;装饰器的规则形式是[schema, getData, customErrorMessage?]schemaTypeBox 定义的 TSchemagetData(ctx, args) data从 Context 中取出待校验的数据ctx.params、ctx.request.body、ctx.query等customErrorMessage可选(ctx, errors) string自定义失败消息。装饰器实现见 src/decorator.ts它包装原方法按顺序对每条规则执行ctx.tValidateWithoutThrow一旦校验失败就调用自定义 handler默认 handler 抛 422invalid_param全部通过后才执行原方法体。ValidateFactory(customHandler)允许你定制失败后的回调如重定向、写日志、渲染自定义错误页。使用约束装饰器内部通过this.ctx取值因此只适用于拥有this.ctx的类controller、service 等。更多用法可以查看仓库测试用例中的delete自定义错误消息与putValidateWithRedirect重定向场景。支持 AJV 对 string 的 transform 校验插件在初始化 AJV 实例时加载了ajv-keywords的transform关键字src/app.ts可以对字符串字段做预处理转换const body { name: david }; ctx.tValidate( Type.Object({ name: Type.String({ minLength: 1, maxLength: 5, transform: [trim] }), }), body, );两点需要注意校验是可以通过的trim 后长度满足要求这是带副作用的校验——会原地改写入参校验后body变成{ name: david }。transform支持的操作trim、toLowerCase、toUpperCase 等由ajv-keywords提供测试用例中的description字段就组合使用了[trim, toLowerCase]。如何写自定义校验规则AJV 的format机制非常开放可以通过config.typeboxValidate.patchAjv给默认 AJV 实例注入自定义规则。例如校验字符串是否为合法 JSON1. 在 config.default.ts 中 patch AJV 实例config.typeboxValidate { patchAjv: (ajv) { ajv.addFormat(json-string, { type: string, validate: (x) { try { JSON.parse(x); return true; } catch (err) { return false; } }, }); }, };2. 使用async someFunc() { const typebox Type.Object({ jsonString: Type.Optional(Type.String({ format: json-string })), }); const res ctx.tValidate(typebox, { a: {a:1} }); // valid const res ctx.tValidate(typebox, { a: wrong{a:1} }); // invalid }同理可以继续 patch 更多规则比如常见的 semver 规范 import { valid } from semver; config.typeboxValidate { patchAjv: (ajv) { ajv.addFormat(json-string, { type: string, validate: (x) { try { JSON.parse(x); return true; } catch (err) { return false; } } }); ajv.addFormat(semver, { type: string, validate: (x) valid(x) ! null, }); } };使用示例async someFunc() { const typebox Type.Object({ version: Type.String({ format: semver }), }); const res ctx.tValidate(typebox, { a: 1.0.0 }); // valid const res ctx.tValidate(typebox, { a: a.b.c }); // invalid }上面是 string 的例子format 同样适用于 number、array 等其他类型。测试 fixture 中就注册了 number 类型的自定义 formatbyte校验 0~255 的整数对应 test/fixtures/apps/typebox-validate-test/config/config.default.ts。全部 JSON Schema 支持的类型参考 json-schema.org 官方文档。patchAjv 的触发时机配置项typeboxValidate.patchAjv在 src/config/config.default.ts 中声明为可选的(ajv: Ajv) void。插件启动时src/app.ts构造函数中创建Ajv2019实例并挂载到this.app.ajv加载ajv-keywords的transform关键字通过ajv-formats注册默认 format 列表并补充kind、modifier两个自定义关键字在configDidLoad生命周期中调用typeboxValidate.patchAjv?.(this.app.ajv)把你配置的自定义规则注入进去。所以自定义 format 只需在配置中声明无需改动插件代码全局 schema 即可直接引用。总结切换到eggjs/typebox-validate之后收益集中在两点解决 TS 项目中参数校验写两遍类型的问题TypeBox 一份定义同时产出运行时校验与编译期类型提升代码复用率与可维护性配合Static推导和Validate装饰器控制器代码更简洁校验走标准 JSON Schema 规范内置更多业界标准 format并有ajv-keywords的 transform 等进阶能力schema 静态化后性能优势明显项目 benchmark 显示吞吐量高出一个数量级。对于已有 egg-validate 代码的项目建议按照简单接口先行、复杂接口跟进的方式渐进式迁移。相关源码、测试与 benchmark 均可在本仓库 plugins/typebox-validate 目录下继续深读。【免费下载链接】egg Born to build better enterprise frameworks and apps with Node.js Koa. https://307.run/eggcode项目地址: https://gitcode.com/gh_mirrors/eg/egg创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

关于本文作者

来自尧图内容编辑团队

尧图内容编辑团队 内容团队

尧图内容编辑团队

本文由尧图网络内容编辑团队执笔。团队由资深项目经理、前端工程师与设计师组成,所有内容均来自亲手交付的真实项目,先讲清问题、再给出可落地的解法。尧图深耕北京网站建设十年,服务过京华建材集团、智造科技等各行业客户,把一线经验沉淀为可复用的行业观察。

  • 十年建站经验,覆盖建材、制造、服务、文创等
  • 项目经理把关选题与事实准确性
  • 工程师与设计师联合撰写专业细节
  • 统一编辑规范,保证文风与排版一致
  • 每月复盘转化数据,迭代选题方向

延伸阅读

相关资讯与近期热门内容

深度阅读推荐

建站决策前值得细读的三篇

网站改版的5个关键决策
2024-08-12

网站改版的5个关键决策

什么时候该改版、改到什么程度、如何避免流量掉光,京华建材集团改版复盘给出答案。

获取专属建站方案

看完文章,把您的行业与预算告诉我们,免费获取一份量身定制的官网建设方案与报价。

立即免费咨询