简体   繁体   English

如何使用 joi 设置正确的模式和验证?

[英]How to set up a proper schema and validation using joi?

I'm currently trying to setup validation using the joi package but I'm running into some issues that most likely revolve around syntax.我目前正在尝试使用 joi 包设置验证,但我遇到了一些最有可能与语法有关的问题。

The schema I've set up is a fairly simple one that checks whether or not a number is valid and/or if the id exists within the database.我设置的模式是一个相当简单的模式,它检查数字是否有效和/或数据库中是否存在 id。

export default router.post('/', async function(req, res, next) {
  const Joi = require('joi');
  // for testing
  if (!Object.keys(req.body).length) {
    req.body = {'tId':'123456789'}
  }

  const data = req.body;

  const schema = Joi.object().keys({
    tId: Joi.string.tId.required()
  });

  Joi.validate(data, schema, (err, value) => {

    if(err){
      res.status(404).json({
        status: 'error',
        message: 'tId not found',
        data: data
      });
    } else {
      res.json({
        status: 'success',
        message: 'Person found',
        data: Object.assign(22, value)
      });
    }
  });
})

The error that I'm currently getting is around tId: Joi.string.tId.required() .我目前得到的错误是tId: Joi.string.tId.required()

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'required' of undefined UnhandledPromiseRejectionWarning: TypeError: 无法读取未定义的“必需”属性

My current research has been primarily around the following link:我目前的研究主要围绕以下链接:

https://www.digitalocean.com/community/tutorials/how-to-use-joi-for-node-api-schema-validation https://www.digitalocean.com/community/tutorials/how-to-use-joi-for-node-api-schema-validation

I tried to mimic the concepts that this tutorial implemented and I think I have somewhat of a decent idea how it works but I'm just having some trouble with the syntax of the library.我试图模仿本教程实现的概念,我认为我对它的工作原理有一些不错的想法,但我只是在库的语法方面遇到了一些问题。

Any links, videos, projects etc that makes good use of the joi library would be extremely helpful.任何能够充分利用 joi 库的链接、视频、项目等都会非常有帮助。

As you guessed, it's just a syntax error.正如您所猜测的,这只是一个语法错误。 Update this part:更新这部分:

const schema = Joi.object().keys({
    tId: Joi.string().required()
});

From Joi.validate , I'm assuming you're Joi v15 or lower, here's the documentation you're looking for- https://joi.dev/api/?v=15.1.1#string---inherits-from-anyJoi.validate ,我假设你是 Joi v15 或更低版本,这里是你正在寻找的文档 - https://joi.dev/api/?v=15.1.1#string---inherits-from -任何

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM