validator kelas ekspres
// using like this
// this.router.post('/register', [validator([DTORegister])], this.registerUsersController)
export function validator(DataTransferObject: any) {
return async function (req: Request, res: Response, next: NextFunction): Promise<OutgoingMessage> {
let errors: any = []
DataTransferObject.forEach(async (DTO: any) => {
const property: Record<string, any> = {}
Object.assign(property, req.body, req.params, req.query)
const errorsResponse: ValidationError[] = await validate(Object.assign(new DTO(), property))
errors.push(errorsResponse)
})
const errorMessage = errors.map((val: ValidationError) => apiResponse(400, Object.values(val.constraints)[0]))
if (errorMessage.length) {
return res.status(status.BAD_REQUEST).json(errorMessage)
}
next()
}
}
Restu Wahyu Saputra