nestjs开发对前端传递过来的数据进⾏校验⼀、局部验证的⽅式
1、安装包
npm i --save class-validator class-transformer
2、⽐如在cat的⽬录下创建⼀个dto的⽂件夹,创建⼀个create.cat.dto.ts的⽂件
import{ IsString, IsInt, MinLength, MaxLength }from'class-validator';
export class CreateCatDto {
@IsString({ message:'必须的字符类型'})
@MinLength(2,{
message:'长度不能⼩于2',
})
@MaxLength(10,{
message:'长度不能超过10',
})
readonly name: string;
@IsInt({ message:'必须的整数'})
readonly age: number;
}
3、在ller.ts中使⽤提交过来的数据约束
@Controller('cat')
export class CatController {
constructor(private readonly catService: CatService){}
@Post()
@HttpCode(HttpStatus.CREATED)
async create(@Body(new ValidationPipe()) createCatDto: CreateCatDto){
Logger.log('-----------创建猫 start--------------');
Logger.log(createCatDto);
Logger.log('-----------创建猫 end--------------');
return'创建猫';
}
...
}
⼆、全局使⽤管道校验(前提是先安装包)
1、在根⽬录下的main.ts⽂件中
import{ NestFactory }from'@nestjs/core';
import{ AppModule }from'./dule';
import{ Logger, ValidationPipe }from'@nestjs/common';
import*as helmet from'helmet';
bootstrap检验方法async function bootstrap(){
const app =ate(AppModule,{
cors:true,// 设置跨站访问
logger:false,
});
// 使⽤跨站脚本攻击类的库
app.use(helmet());
/
/ 给请求添加prefix
app.setGlobalPrefix('api/v1');
// 全局使⽤管道
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000,()=>{
Logger.log('服务已经启动,请访问localhost:3000');
});
}
bootstrap();
2、在ller.ts中使⽤提交过来的数据约束
@Controller('cat')
export class CatController {
constructor(private readonly catService: CatService){}
@Post()
@HttpCode(HttpStatus.CREATED)
async create(@Body() createCatDto: CreateCatDto){// 这⾥就不需要使⽤校验约束    Logger.log('-----------创建猫 start--------------');
Logger.log(createCatDto);
Logger.log('-----------创建猫 end--------------');
return'创建猫';
}
...
}
3、前端传递数据错误的提⽰
{
"statusCode":400,
"error":"Bad Request",
"message":[
{
"target":{
"name":"哈⼠奇222",
"age":"20"
},
"value":"20",
"property":"age",
"children":[],
"constraints":{
"isInt":"必须的整数"
}
}
]
}
三、约束@Param接受的数据类型
1、安装包
npm i --save class-validator class-transformer
2、直接在ller.ts中使⽤
@Controller('cat')
export class CatController {
constructor(private readonly catService: CatService){}
...
@Get(':id')
@HttpCode(HttpStatus.OK)
async findOne(
@Param('id',new ParseIntPipe()) id,// 使⽤内置的转换整数的管道
@Query() query:{[propsName: string]: any },
){
Logger.log('-----------查⼀个 start--------------');
Logger.log(id);
Logger.log(query);
Logger.log('-----------查⼀个 end--------------');
return await this.catService.findOne(id);
}
...
}
四、⾃⼰创建管道⽣成验证规则
上⾯使⽤的是内置的管道约束,如果没有,我们可以⾃⼰创建约束管道
1、在src⽬录下创建⼀个⽂件夹pipe
2、使⽤命令⽣成管道
nest g pi pipe/parseInt
nest g pi pipe/parseInt --no-spec # 不⽣成带测试⽂件的
3、书写管道代码
import{
ArgumentMetadata,
Injectable,
PipeTransform,
BadRequestException,
}from'@nestjs/common';
@Injectable()
export class ParseIntPipe implements PipeTransform<string, number>{
transform(value: string, metadata: ArgumentMetadata): number {
const val =parseInt(value,10);
if(isNaN(val)){
throw new BadRequestException('验证错误');
}
return val;
}
}
4、直接在ller.ts中使⽤(和内置的⼀样的使⽤)
五、⾃定义返回错误格式
1、命令⽅式⽣成⾃⼰的校验管道
nest g pi pipe/Validation --no-spec
2、管道的书写
/*
* @Description:⾃定义管道,根据⾃⼰格式返回错误信息
* @Author: ⽔痕
* @Github: github/kuangshp
* @Email: 332904234@qq
* @Company:
* @Date: 2019-07-24 14:26:27
* @LastEditors: ⽔痕
* @LastEditTime: 2019-07-24 14:46:45
*/
import{
ArgumentMetadata,
Injectable,
PipeTransform,
BadRequestException,
Logger,
}from'@nestjs/common';
import{ validate }from'class-validator';
import{ plainToClass }from'class-transformer';
import*as _ from'lodash';
@Injectable()
export class ValidationPipe implements PipeTransform<any>{ async transform(value: any, metadata: ArgumentMetadata){
const{ metatype }= metadata;
if(!metatype ||!Validate(metatype)){
return value;
}
const object =plainToClass(metatype, value);
const errors =await validate(object);
Logger.log(errors);
if(errors.length >0){
// 遍历全部的错误信息,返回给前端
const errorMessage = errors.map(item =>{
return{
currentValue: item.value,
[item.property]: _.straints)[0],
};
});
throw new BadRequestException(errorMessage);
}
return value;
}
private toValidate(metatype: any): boolean {
const types =[String, Boolean, Number, Array, Object];
return!types.includes(metatype);
}
}
3、使⽤⽅式和上⾯的⼀样的
4、返回的错误提⽰
{
"data":{
"error":[
{
"currentValue":"哈⼠奇21111111111111",
"name":"长度不能超过10"
},
{
"age":"年龄不能为空"
}
]
},
"message":"请求失败",
"code":1,
"url":"/api/v1/cat"
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。