Skip to content

Instantly share code, notes, and snippets.

@3zrv
Created May 10, 2023 08:27
Show Gist options
  • Select an option

  • Save 3zrv/e49e611242d594c839b4a007a1c78dac to your computer and use it in GitHub Desktop.

Select an option

Save 3zrv/e49e611242d594c839b4a007a1c78dac to your computer and use it in GitHub Desktop.
Joi validation example
import Joi from 'joi';
import _ from 'lodash';
const validate = (schema) => (req, res, next) => {
const validSchema = _.pick(schema, ['params', 'query', 'body']);
const object = _.pick(req, Object.keys(validSchema));
const { error, value } = Joi.compile(validSchema)
.prefs({ errors: { label: 'path', wrap: { label: false } }, abortEarly: false })
.validate(object);
if (error) {
return next(error);
}
Object.assign(req, value);
return next();
};
const login = {
body: Joi.object().keys({
userName: Joi.string().required(),
password: Joi.string().required()
})
};
router.post('/login', validate(login), authController.login);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment