Created
May 10, 2023 08:27
-
-
Save 3zrv/e49e611242d594c839b4a007a1c78dac to your computer and use it in GitHub Desktop.
Joi validation example
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
| 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