[英]Fastify schema validation isn't working. Do I have something configured the wrong way?
我想弄清楚為什么模式驗證在 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 }
})
當我使用郵遞員對其進行測試時,我可以將任何鍵和值與正文一起發送,並且一切順利。 似乎根本沒有檢查。 響應也是一樣。 我正在使用 Fastify 2.11.0 版
編輯:這是我發送的 json 正文:
{
"name": "Test",
"parentId": 5555555,
"foo": "bar"
}
這是我希望失敗的內容:
{
"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"
}
如果我發送此機構,它會順利通過。 如何將其配置為在所有這些情況下都失敗?
您的架構使用有一些修復要應用:
'2xx'
或在reply
對象中設置正確的代碼additionalProperties
required
字段,則所有字段都是可選的這是一個阻塞示例:
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'"
}
*/
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.