在任意函数中使用fastify-json模式验证



Fastify有一些非常棒的json模式支持。(链接(

然而,我现在也想在我的业务逻辑中使用我用fastify.addSchema(..(添加的模式。例如(伪代码(:

schema = fastify.getSchema("schema1")
if (schema.validate(data)) {
console.log("ok");
} else {
console.log("not ok");
}

我怎样才能做到这一点?

现在,在Fastify中,一个路由有一组验证函数。这些函数之所以存在,是因为您在{ schema: {} }路由中设置了它们配置

因此,首先,如果您不在路由中设置这些模式,您将无法访问它们。getSchema函数检索模式对象,而不是che编译函数。关系不是1:1,因为验证函数可能通过$ref关键字使用更多的模式。

存档所需内容的唯一方法是对内部Fastify进行猴子补丁(非常不鼓励(或者打开对项目的功能请求。

这里是一个示例,正如您所看到的,您只能在路由的上下文中获取路由的验证函数。因此,它远不是一个灵活的用法。

const fastify = require('fastify')({ logger: true })
const {
kSchemaBody: bodySchema
} = require('fastify/lib/symbols')

fastify.post('/', {
schema: {
body: {
$id: '#schema1',
type: 'object',
properties: {
bar: { type: 'number' }
}
}
}
}, async (request, reply) => {
const schemaValidator = request.context[bodySchema]
const result = schemaValidator({ bar: 'not a number' })
if (result) {
return true
}
return schemaValidator.errors
})
fastify.inject({
method: 'POST',
url: '/',
payload: {
bar: 33
}
}, (err, res) => {
console.log(res.json())
})

最新更新