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

如何在Fastify实例中编程禁用所有路由JSON Schema验证并保留Schema?

如何在Fastify中全局禁用JSON Schema验证但保留Schema定义

问题场景

我需要以编程方式禁用Fastify实例中所有路由的JSON Schema验证,现有路由示例如下:

module.exports = async (fastify, opts) => {
  fastify.get('/stations.json', {schema: opts.schema}, async req => {
    return {
      // 接口返回数据
    };
  });
}

之前试过用onRoute钩子清空路由的schema:

// 全局配置部分
fastify.addHook('onRoute', route => {
  if (config.validation === false && route.schema) {
    route.schema = null
    console.log('Route disable:',route.path)
  }
})

但这个方法会破坏swagger-ui,因为Schema被清空后无法生成接口文档。我希望只跳过验证逻辑,同时保留每个路由的Schema定义,猜测可以用fastify.setValidatorCompiler()实现,但不清楚具体用法,需要的是绕过验证函数执行,而不是返回空验证。


解决方案:自定义验证编译器跳过验证

直接通过setValidatorCompiler返回一个始终resolve的函数,这样既保留路由的Schema(供swagger生成文档),又不会执行任何验证逻辑。

代码实现

// 初始化Fastify实例时配置
const fastify = require('fastify')({ logger: true });

// 替换为你的全局配置开关
const shouldDisableValidation = config.validation === false;

if (shouldDisableValidation) {
  fastify.setValidatorCompiler(() => {
    // 返回一个永远验证通过的函数
    return () => Promise.resolve();
  });
}

// 正常注册你的路由
fastify.register(require('./routes/stations'));

fastify.listen({ port: 3000 }, (err) => {
  if (err) throw err;
});

原理说明

  • setValidatorCompiler是Fastify获取路由验证逻辑的核心入口,Fastify会为每个路由的Schema调用这个方法生成对应的验证函数。
  • 我们返回的函数不做任何实际验证,直接返回resolved的Promise,Fastify会认为所有请求都验证通过,但路由的Schema定义完全保留,swagger-ui依然能正常读取这些Schema生成接口文档。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 18:20:16