fastify的自定义格式化程序



我想为fastify添加一个自定义模式格式化程序。

import fastify from 'fastify'
import AjvCompiler from '@fastify/ajv-compiler'
const ajvFormatter = AjvCompiler(ajv);
ajvFormatter.addFormat('new-format', /hello/);
const app = fastify({
schemaController: {
compilersFactory: {
buildValidator: ajvFormatter
}
}
})

我添加了格式,但仍然给出错误:

Failed building the validation schema for POST: /hey, due to error unknown format 
"new-format" ignored in schema at path

我想最新的fastify不支持这个功能。

您使用@fastify/ajv-compiler模块的方式不对。它根本不接受ajv输入参数。而不是导出CCD_ 3方法。

您需要使用customOption选项:

const fastify = require('fastify')
const app = fastify({
logger: true,
ajv: {
customOptions: {
formats: {
'new-format': /hello/,
},
},
},
})
app.get(
'/:hello',
{
schema: {
params: {
type: 'object',
properties: {
hello: {
type: 'string',
format: 'new-format',
},
},
},
},
},
async (request, reply) => {
return request.params
}
)
app.listen(8080, '0.0.0.0')
// curl http://127.0.0.1:8080/hello
// curl http://127.0.0.1:8080/hello-foo

最新更新