You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fastify校验序列化场景下如何在handler中获取已校验的过滤数据

解决方案

核心逻辑:Fastify 会自动将校验通过后的转换/过滤值挂载到对应请求属性上,你只需调整 validatorCompiler 配置和 Joi 校验参数即可:

第一步:调整校验配置

你当前的 validatorCompiler 没有适配 Fastify 的返回值约定,也没有开启 Joi 字段过滤能力,修改如下:

const Joi = require('@hapi/joi')

fastify.post('/the/url', {
  schema: {
    body: Joi.object().keys({
      hello: Joi.string().required()
    }).required()
  },
  validatorCompiler: ({ schema, method, url, httpPart }) => {
    return data => {
      // 开启stripUnknown来过滤未在schema中定义的字段
      const result = schema.validate(data, { stripUnknown: true })
      if (result.error) {
        return { error: result.error }
      }
      // 校验通过时返回value,Fastify会自动用这个值覆盖对应请求属性
      return { value: result.value }
    }
  }
}, handler)

如果所有路由都使用Joi校验,也可以全局注册validatorCompiler,无需每个路由单独配置:

fastify.setValidatorCompiler(({ schema }) => {
  return data => {
    const result = schema.validate(data, { stripUnknown: true })
    return result.error ? { error: result.error } : { value: result.value }
  }
})

第二步:在handler中直接读取过滤后的数据

修改完配置后,req.body 就是校验通过且过滤后的结果,直接读取即可:

const handler = (req, reply) => {
  // req.body仅包含schema中定义的字段,自动过滤了所有未声明的参数
  console.log(req.body.hello)
}

内容的提问来源于stack exchange,提问作者hyden97

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 03:27:05