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
2 Answers
Reset to default 5It 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