0
votes

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...

1
I don't know why your schema type is object, because from my typescript object is error, so I change it to any. export const validator = (schema: any) => { ... } and it's working fine. - Titus Sutio Fanpula

1 Answers

1
votes

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