簡體   English   中英

有沒有一種方法可以在嵌套有效負載上使用 JOI 驗證未知密鑰?

[英]Is there's a way to validate unknown keys with JOI on nested payloads?

我有一個使用 Joi 驗證傳入請求的中間件。

export default (schema: any) => async (req: Request, res: Response, next: NextFunction) => {
  try {
    const validation = schema.validate(req, { abortEarly: false })

    if (validation.error) throw validation.error

    return next()
  } catch (error) {
    return res.status(400).json({ error: error.details })
  }
}

為了測試,提議,我的架構如下

const schema = Joi.object({
  headers: Joi.object()
    .keys({
      page: Joi.string().required()
    })
    .unknown(true)
    .label('headers'),
  body: Joi.object({
    page: Joi.string().required()
  })
})

我正在用 Postman 測試這個 function。當我不發送 header 時,它失敗但顯示以下錯誤:

  • '用戶代理':'PostmanRuntime/7.29.0'
  • 接受:' / ',
  • 'accept-encoding': 'gzip, deflate, br',
  • 連接:'保持活動'

我希望能夠僅驗證模式中的“頁面”字段,而忽略上面的任何其他字段。

更改您的驗證並將 stripUnknown 選項添加為 true:

const validation = schema.validate(req, { abortEarly: false, stripUnknown:true })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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