express-template/middlewares/ValidateDto.js

47 lines
1.1 KiB
JavaScript
Raw Normal View History

2021-06-19 09:55:58 +00:00
const { validate } = require('class-validator')
const { plainToClass } = require('class-transformer')
const data_from_array = ['body','query','params','cookie']
/**
*
* @param {new ()=>void} dto
* @param {'body'|'query'|'params'|'headers'|'cookie'} from
* @returns {RequestHandler}
*/
module.exports = function (dtoFunc,from) {
if(!data_from_array.includes(from)) {
throw new Error('校验数据源无效')
}
return async function (req,res,next) {
const dto = plainToClass(dtoFunc,req[from],{ enableImplicitConversion:true,excludeExtraneousValues:true })
req[from] = dto
try{
var errors = await validate(dto)
}catch(err) {
console.error('数据校验过程中报错')
res.status(500)
res.error('内部错误',500)
return
}
if(errors.length === 0) {
console.log('数据校验通过')
return next()
}
console.error('数据校验不通过',errors)
const error = errors[0]
const errorMsg = Object.entries(error.constraints)[0][1]
res.error(errorMsg,400,{ is_validate:true,field:error.property,from })
}
}