init
This commit is contained in:
47
middlewares/ValidateDto.js
Normal file
47
middlewares/ValidateDto.js
Normal file
@@ -0,0 +1,47 @@
|
||||
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 })
|
||||
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user