I am currently in the process of developing a unique middleware function to work with Joi that will be placed on my routes for validating a Joi schema.
In the past, I have created middlewares for JWT validation without passing any parameters, and they worked effectively.
Configuring the route and applying the middleware function
app.route('/identity').post([validator(identitySchema)], this.identityController.createIdentity);
The validator middleware function
export const validator = (schema: object) => {
return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
console.log('req: ' + req.body); //prints req: [object Object]
console.log('schema: ' + schema); //prints schema: [object Object]
//VALIDATION LOGIC GOES HERE
};
};
If I had written just
app.route('/identity').post([validator], this.identityController.createIdentity);
export const validator(req: Request, res: Response, next: NextFunction) => {
It would have automatically picked up req, res, etc...