u84*_*six 1 javascript jsonschema fastify
我试图找出为什么模式验证在 Fastify 中不起作用。我有以下代码:
const postOptions = {
schema: {
body: {
type: 'object',
properties: {
name: { type: 'string' },
parentId: { type: 'number' },
requiredKey: { foo: { type: 'string'} }
}
},
response: {
201: {
type: 'object',
properties: {
id: { type: 'number'},
name: { type: 'string'},
parentId: { type: 'number' }
}
}
}
}
}
fastify.post('/sponsor', postOptions, async (request, reply) => {
console.log(`POST /sponsor called`)
return { id: 2, name: 'Zenotis', parentId: 1 }
})
Run Code Online (Sandbox Code Playgroud)
当我使用邮递员测试它时,我可以通过正文发送任何键和值,并且一切顺利。好像根本就没有检查过。与响应相同。我使用的是 Fastify 版本 2.11.0
编辑:这是我发送的 json 正文:
{
"name": "Test",
"parentId": 5555555,
"foo": "bar"
}
Run Code Online (Sandbox Code Playgroud)
这是我预计会失败的情况:
{
"myName": "the field is not name",
"parentID": "The D is capitalized and this is a string",
"bar": "where did this field come from, it's not foo"
}
Run Code Online (Sandbox Code Playgroud)
如果我发送这具尸体,一切都会顺利。我如何将其配置为在所有这些情况下失败?
您的架构使用需要进行一些修复:
'2xx'或设置正确的代码replyadditionalPropertiesrequired在模式中设置字段,则所有字段都是可选的这是一个阻塞示例:
const fastify = require('fastify')()
const postOptions = {
schema: {
body: {
type: 'object',
additionalProperties: false, // it will remove all the field that is NOT in the JSON schema
required: [
'name',
'parentId',
'requiredKey'
],
properties: {
name: { type: 'string' },
parentId: { type: 'number' },
requiredKey: { foo: { type: 'string' } }
}
},
response: {
201: {
type: 'object',
properties: {
id: { type: 'number' },
name: { type: 'string' },
parentId: { type: 'number' }
}
}
}
}
}
fastify.post('/sponsor', postOptions, async (request, reply) => {
console.log('POST /sponsor called')
reply.code(201) // if you don't set the code 201, the response schema you set will not work
return request.body
})
fastify.inject({
method: 'POST',
url: '/sponsor',
payload: {
name: 'Test',
parentId: 5555555,
foo: 'bar'
}
}, (_, res) => {
console.log(res.json())
/* it will print
{
statusCode: 400,
error: 'Bad Request',
message: "body should have required property 'requiredKey'"
}
*/
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5223 次 |
| 最近记录: |