Created
July 29, 2019 12:44
-
-
Save RafaPegorari/54ce221a68ba599c88807a936f767b35 to your computer and use it in GitHub Desktop.
Validate route parameters in middleware of express using Joi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// file: lib/middleware-joi-validator/index.js | |
const Joi = require('@hapi/joi'); | |
const validate = (schema, options) => { | |
options = options || {} | |
const validateRequest = (req, res, next) => { | |
const toValidate = {} | |
if (!schema) { | |
return next() | |
} | |
['params', 'body', 'query'].forEach(key => { | |
if (schema[key]) { | |
toValidate[key] = req[key] | |
} | |
}) | |
const onValidationComplete = (err) => { | |
if (err) { | |
return res.status(400).json(err.details) | |
} | |
return next() | |
} | |
return Joi.validate(toValidate, schema, options, onValidationComplete) | |
} | |
return validateRequest | |
} | |
module.exports = validate | |
// --------------------------------------------------------------------------- | |
// file: src/routes/lorem-ipsum/getLorem.js | |
const validator = require('../../lib/middleware-joi-validator') | |
const Joi = require('joi') | |
var schema = { | |
query: { | |
limit: Joi.number().default(10).min(10).max(100), | |
offset: Joi.number().default(10).min(10).max(100) | |
}, | |
body: { | |
name: Joi.string().required() | |
} | |
} | |
const middleware = validator(schema) | |
const getLorem = async (req, res) => { | |
// End-point | |
} | |
module.exports = [ middleware, getLorem ] | |
// --------------------------------------------------------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment