我将dto文件全收集到一个dto文件夹里,可按照文档建议。
1.安装依赖
pnpm i --save class-validator class-transformer
参考文档
https://github.com/typestack/class-transformerhttps://github.com/typestack/class-transformer
https://github.com/typestack/class-validatorhttps://github.com/typestack/class-validator2. 新建一个用户登录的验证dto文件
src/dto/login-manage.dto
import { IsNotEmpty, IsString, Length } from "class-validator"
/**
* 管理员登录
* 加入验证管道pipe
*/
export class LoginManageDto {
@IsString()
@IsNotEmpty({ message: '管理员不能为空' })
username: string
@IsString()
@IsNotEmpty({ message: '密码不能为空' })
@Length(6, 16, {
message: '密码长度必须在6-16位之间'
})
password: string
}
3.在controller文件中加入该管道dto文件
import { Body, Controller, Post } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LoginManageDto } from 'src/dto/login-manage.dto';
/**
* 用户鉴权
*/
@Controller('admin/auth')
export class AuthController {
constructor(
private authService: AuthService,
) {}
/**
* 登录
* 可在@Body()引入内置管道pipe
*/
@Post('/login')
async login(@Body() dto: LoginManageDto) {
const { username, password } = dto;
let token = await this.authService.manageLogin(username, password);
//登录成功 返回token值
return {
token
}
}
}
4.在main.ts中加入全局管道
//全局配置管道pipe拦截器
app.useGlobalPipes(new ValidationPipe({
//去除在类上不存在的字段
//whitelist: true
}));
5.在filter拦截器中,验证异常返回的是status: 400
6. 这样做比较简单,不用想太复杂,也可以用内置管道
@Get('/find')
async getManage(@Query('id', ParseIntPipe) id: number) {
console.log(typeof id)
}
7. 唯一差别是我文件是使用filter做了全局拦截的。