Nestjs 管道验证DTO

本文详细介绍了如何在NestJS应用中创建验证管道,使用class-validator和class-transformer进行数据校验,以及如何在全局范围内注册和使用验证。包括创建验证管道、安装验证器、controller中的使用以及在main.ts中配置全局验证。
摘要由CSDN通过智能技术生成

一、创建验证管道pipe

1、创建p模块

nest g res p

2、创建验证管道

nest g pi p

二、安装验证器 

npm i --save class-validator class-transformer

代码 :

import { IsNotEmpty, IsString } from "class-validator";
import { isString } from "class-validator/types/decorator/decorators";

export class CreatePDto {
    @isNotEmpty()   // 验证是否为空
    @isString()     // 验证是否为字符串
    name: string;
    
    @IsNotEmpty()
    age: number
}

 截图:

 三、controller 使用管道

四、transform 实现验证 

p.pipe.ts 文件 逻辑代码:

通过 validate 验证 DTO 返回一个promise 的错误信息 

import { ArgumentMetadata, HttpException, HttpStatus, Injectable, PipeTransform } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';

@Injectable()
export class PPipe implements PipeTransform {
    async transform(value: any, metadata: ArgumentMetadata) {
        const DTO = plainToInstance(metadata.metatype, value);
        
        const errors = await validate(DTO);
        if(errors.length > 0) {
            throw new HttpException(errors, HttpStatus.BAD_REQUEST);        
        }
        return value;
    }
}

 

 五、注册全局DTO验证管道

main.ts 文件添加一下内容:

import { VersioningType } from '@nestjs/common';

app.useGlobalPipes(new ValidationPipe());
import { VersioningType, ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as session from 'express-session';
import { NestExpressApplication } from '@nestjs/platform-express/interfaces';
import { join } from 'path';

async function bootstrap() {
    const app = await NestFactory.create<NestExpressApplication>(AppModule);
    app.useGlobalPipes(new ValidationPipe());
    await app.listen(3000);
}
bootstrap();

请求截图:

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于 NestJS 的用户注册、验证和登录功能,可以通过以下步骤来实现: 1. 安装必要的依赖 在项目根目录下运行以下命令来安装必要的依赖: ``` npm install --save @nestjs/passport passport passport-local bcrypt npm install --save-dev @types/passport-local ``` 2. 创建用户模型 在 `src/auth` 目录下创建 `user.entity.ts` 文件,并定义用户模型,例如: ```typescript import { BaseEntity, Entity, PrimaryGeneratedColumn, Column, Unique } from 'typeorm'; @Entity() @Unique(['username']) export class User extends BaseEntity { @PrimaryGeneratedColumn() id: number; @Column() username: string; @Column() password: string; } ``` 3. 创建用户注册 DTO 在 `src/auth/dto` 目录下创建 `auth.dto.ts` 文件,并定义用户注册 DTO,例如: ```typescript export class AuthDto { username: string; password: string; } ``` 4. 创建用户认证服务 在 `src/auth` 目录下创建 `auth.service.ts` 文件,并定义用户认证服务,例如: ```typescript import { Injectable, UnauthorizedException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { User } from './user.entity'; import { AuthDto } from './dto/auth.dto'; import * as bcrypt from 'bcrypt'; @Injectable() export class AuthService { constructor( @InjectRepository(User) private userRepository: Repository<User>, ) {} async signUp(authDto: AuthDto): Promise<void> { const { username, password } = authDto; const user = new User(); user.username = username; user.password = await bcrypt.hash(password, 10); await user.save(); } async validateUser(username: string, password: string): Promise<User> { const user = await this.userRepository.findOne({ where: { username } }); if (!user || !(await bcrypt.compare(password, user.password))) { throw new UnauthorizedException('Invalid username or password'); } return user; } } ``` 5. 创建本地策略 在 `src/auth` 目录下创建 `local.strategy.ts` 文件,并定义本地策略,例如: ```typescript import { Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy } from 'passport-local'; import { AuthService } from './auth.service'; @Injectable() export class LocalStrategy extends PassportStrategy(Strategy) { constructor(private authService: AuthService) { super(); } async validate(username: string, password: string): Promise<any> { const user = await this.authService.validateUser(username, password); return user; } } ``` 6. 创建认证模块 在 `src/auth` 目录下创建 `auth.module.ts` 文件,并定义认证模块,例如: ```typescript import { Module } from '@nestjs/common'; import { PassportModule } from '@nestjs/passport'; import { TypeOrmModule } from '@nestjs/typeorm'; import { AuthService } from './auth.service'; import { LocalStrategy } from './local.strategy'; import { UserController } from './user.controller'; import { User } from './user.entity'; @Module({ imports: [TypeOrmModule.forFeature([User]), PassportModule], providers: [AuthService, LocalStrategy], controllers: [UserController], }) export class AuthModule {} ``` 7. 创建用户控制器 在 `src/auth` 目录下创建 `user.controller.ts` 文件,并定义用户控制器,例如: ```typescript import { Body, Controller, Post } from '@nestjs/common'; import { AuthService } from './auth.service'; import { AuthDto } from './dto/auth.dto'; @Controller('users') export class UserController { constructor(private authService: AuthService) {} @Post('signup') async signUp(@Body() authDto: AuthDto): Promise<void> { await this.authService.signUp(authDto); } } ``` 8. 配置认证路由 在 `src/app.module.ts` 文件中配置认证路由,例如: ```typescript import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { AuthModule } from './auth/auth.module'; import { User } from './auth/user.entity'; @Module({ imports: [ TypeOrmModule.forRoot({ type: 'sqlite', database: 'database.sqlite', entities: [User], synchronize: true, }), AuthModule, ], }) export class AppModule {} ``` 9. 配置认证守卫 在需要进行认证的路由上配置认证守卫,例如: ```typescript import { Controller, Get, UseGuards } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Controller('cats') export class CatsController { @Get() @UseGuards(AuthGuard('local')) findAll() { // 仅经过认证的用户才能访问该路由 } } ``` 以上就是 NestJS 实现用户注册、验证和登录功能的步骤。希望对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值