最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to validate variable is actually a joi schema? - Stack Overflow

programmeradmin0浏览0评论

I'm trying to create a reusable function which you can pass in a joi schema and run validation against req.body. I want to validate my variable schema to ensure that it's a valid joi schema.

Is there a way to do this?

function validatePayload(schema) {
  return (req, res, next) => {
    const valid = joi.validate(req.body, schema)
    if (valid.error) {
      return handleErr(res, HttpStatus.BAD_REQUEST, valid.error.details[0].message)
    }

    return next()
  }
}

I'm trying to create a reusable function which you can pass in a joi schema and run validation against req.body. I want to validate my variable schema to ensure that it's a valid joi schema.

Is there a way to do this?

function validatePayload(schema) {
  return (req, res, next) => {
    const valid = joi.validate(req.body, schema)
    if (valid.error) {
      return handleErr(res, HttpStatus.BAD_REQUEST, valid.error.details[0].message)
    }

    return next()
  }
}
Share Improve this question asked Jan 28, 2019 at 21:19 CatfishCatfish 19.3k60 gold badges213 silver badges358 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

It appears that Joi internally validates a schema by checking if Joi constructor is found in the schema prototype chain, therefore, you probably can use the same validation:

const mySchema = Joi.object().keys({
  username: Joi.string(),
  password: Joi.string()
});

const isValidSchema = mySchema instanceof Joi.constructor;

console.log(isValidSchema);
<script src="https://cdn.jsdelivr/npm/[email protected]/dist/joi-browser.min.js"></script>

There is now a dedicated method to check if supplied object is a schema

const Joi = require('@hapi/joi')

const schema = Joi.any();
Joi.isSchema(schema); // true

const notSchema = {}
Joi.isSchema(notSchema); // false

https://hapi.dev/module/joi/api/?v=17.1.1#isschemaschema-options

发布评论

评论列表(0)

  1. 暂无评论