Validador de clase expresa
// using like this
// this.router.post('/register', [validator(DTORegister)], this.registerUsersController)
import { validate, ValidationError } from 'class-validator'
import { StatusCodes as status } from 'http-status-codes'
import { Request, Response, NextFunction } from 'express'
import { OutgoingMessage } from 'http'
import { apiResponse } from '@helpers/helper.apiResponse'
export function validator(DataTransferObject: any) {
return async function (req: Request, res: Response, next: NextFunction): Promise<OutgoingMessage> {
const errors: ValidationError[] = await validate(Object.assign(new DataTransferObject(), req.body))
const errorMessage = errors.map((val: ValidationError) => {
return apiResponse(400, Object.values(val.constraints)[0])
})
if (errorMessage.length) {
return res.status(status.BAD_REQUEST).json(errorMessage)
}
next()
}
}
Restu Wahyu Saputra