I'm trying to create a custom middleware function to use with Joi that I will place on my routes that I can pass a Joi schema to validate.
I have made middlewares for checking JWTs before, but those did not pass a parameter with them, and were fine.
Setting up the route and passing the middleware function
app.route('/identity').post([validator(identitySchema)], this.identityController.createIdentity);
validator middleware function
export const validator = (schema: object) => {
return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
console.log('req: ' + req.body); //outputs req: [object Object]
console.log('schema: ' + schema); //outputs schema: [object Object]
//DO VALIDATION HERE
};
};
If I had just done
app.route('/identity').post([validator], this.identityController.createIdentity);
export const validator(req: Request, res: Response, next: NextFunction) => {
It would have picked up the req, res, etc...
This is my middleware Joi validator
In my route
import express from 'express'
import checkJoi from '../middlewares/check-joi'
import Joi from '@hapi/joi'
const router = new express.Router()
const schemaIndex = Joi.object({
addressId: Joi.number().required(),
products: Joi.array().items(
Joi.object().keys({
id: Joi.number().required(),
quantity: Joi.number().required()
})
).required()
})
router.post('/', checkJoi(schemaIndex), myController.requestUser)
export default router
Middleware Joi Validator
export default (schema) => {
return (req, res, next) => {
const { error } = schema.validate(req.body)
const valid = error == null
if (valid) {
next()
} else {
const { details } = error
const errorsDetail = details.map(i => i.message)
res.status(422).json({
status: false,
error: errorsDetail
})
}
}
}
i hope, i've helped you
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.