簡體   English   中英

Fastify 模式驗證不起作用。 我是否以錯誤的方式配置了某些東西?

[英]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"
}

如果我發送此機構,它會順利通過。 如何將其配置為在所有這些情況下都失敗?

您的架構使用有一些修復要應用:

  • 如果您不設置狀態代碼 201,則您設置的響應模式將不起作用。 使用'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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM