使用 fastify 和路由上的模式对象,我尝试添加更多验证。 fastify 使用(用于身体验证)ajv。按照 fastify 文档和代码,要添加 ajv 插件,我需要这样做:
const fastify = require('fastify')({
ajv: {
plugins: [
require('ajv-merge-patch')
]
}
})
文档位于此处
问题是,当我们尝试添加此插件时,我收到此错误:
Cannot read property 'code' of undefined"
,这是堆栈错误:
TypeError: Cannot read property 'code' of undefined
at addFormats (/test-api/node_modules/ajv-formats/dist/index.js:30:26)
at Array.formatsPlugin (/test-api/node_modules/ajv-formats/dist/index.js:15:5)
at ValidatorCompiler (/test-api/node_modules/fastify/lib/schema-compilers.js:42:16)
at buildCompilerFromPool (/test-api/node_modules/fastify/lib/schema-compilers.js:20:22)
at Boot.<anonymous> (/test-api/node_modules/fastify/lib/route.js:269:39)
at Object.onceWrapper (events.js:421:28)
at Boot.emit (events.js:327:22)
at /test-api/node_modules/avvio/boot.js:153:12
at /test-api/node_modules/avvio/plugin.js:269:7
at done (/test-api/node_modules/avvio/plugin.js:201:5)"
我在这段代码中遇到了这个错误:
const server: FastifyInstance<Server, IncomingMessage, ServerResponse > = fastify({
ignoreTrailingSlash: true,
logger: true,
ajv: {
plugins: [
require('ajv-formats')
]
}
})
async function run (): Promise<string> {
server.addHook('onRoute', (options) => console.log(options))
await server.register(helmet)
await server.register(cors)
return server.listen(3000, 'localhost')
}
有人能够将
ajv-formats
与 fastify 一起使用吗?或者你能帮我吗?
提前致谢!
我遇到了同样的问题,并决定调查原因。问题是
ajv-formats
取决于 ajv 8.x.x
,而 fastify
取决于 ajv 6.x.x
。这两者是不相容的。
有多种解决方案
fastify
支持ajv 8.x.x
。这是一项正在进行中ajv
-插件中,并将其添加到 fastify
。插件是一个将 ajv
实例作为第一个参数 1 的函数。您可以在那里添加格式,看看 ajv-formats
看看它是如何完成的。ajv-formats
。遗憾的是,支持 ajv-formats
的最后一个版本是 0.2.0(查看 package.json)。在我看来这不是一个好的选择
插件也可以采用选项,但没有 Typescript 类型可以将此类插件添加到 ajv 6.x.x
。
fastify
之后,我只是按照文档
中的建议使用此 Ajv 实例在 Fastify 服务器中进行模式编译。
import Ajv from "ajv";
import ajvFormats from "ajv-formats";
import ajvErrors from "ajv-errors";
const ajv = new Ajv({
removeAdditional: true,
useDefaults: true,
coerceTypes: true,
allErrors: true
});
ajvFormats(ajv);
ajvErrors(ajv, { singleError: true });
export { ajv };
它工作没有任何问题。使用常规 JavaScript 可以实现相同的结果。
fastify.setValidatorCompiler((opt) => ajv.compile(opt.schema));
"ajv-merge-patch": "^4.1.0",
"fastify": "^3.9.2",
"fastify-cors": "^5.1.0",
"fastify-helmet": "^5.1.0",
谢谢大家!