3-3:注册

4 阅读1分钟

使用nestJS实现用户注册的功能(使用email和password完成注册) 这里我们使用bcrypt,原因是它非常的简单,只需要传入加密的明文以及加密轮数即可。下面是一个简单示例。

import * as bcrypt from 'bcrypt';

const saltOrRounds = 10;
const password = 'random_password';
const hash = await bcrypt.hash(password, saltOrRounds);

1.创建校验模块

执行命令:
nest g module auth
nest g controller auth
nest g service auth 于是在src目录下创建了auth文件夹,其中包含controller,module,service三个文件。

2.安装依赖

执行命令: pnpm add bcrypt
pnpm add @types/bcrypt -D

3.在auth.service.ts中实现注册的逻辑

import { Injectable, UnauthorizedException } from '@nestjs/common';
import * as bcrypt from 'bcrypt';

export class AuthClass{
    constuctor(private readonly userService:UserService){}
    async signUP(email:string,password:string):Promise<any>{
        const user = await this.userService.findOne(email);
        if(user){
            throw new ConflictException('user with this email already exists');
        }
        //hash password,create user
        const hash = await bycrypt(password,10);
        
        await this.userService.create({email,password})
        
        //这里应该返回一个token,目前先简单返回一个email
        return {
            email
        }
    }
}

4.在controller中使用service中的逻辑

先定义我们的SignUpDto

import { IsEmail, IsString, MinLength } from 'class-validator';

export class SignUpDto {
  @IsEmail()
  email: string;

  @IsString()
  @MinLength(6)
  password: string;
}

然后在controller中写上对应路由的处理逻辑

import { Body, Controller, Post, HttpCode } from '@nestjs/common';
import { AuthService } from './auth.service';
import { SignUpDto } from './dto/sign-up.dto.js';

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Post('register')
  signIn(@Body() signUpDto: SignUpDto) {
    return this.authService.signUp(signInDto.email, signInDto.password);
  }
}

最后别忘记将userModule导出,并在auth.module.ts中导入userModule

import { Module } from '@nestjs/common';
import { UserService } from './user.service';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { User } from './entities/user.entity';
@Module({
  imports: [MikroOrmModule.forFeature([User])],

  providers: [UserService],
  exports: [UserService],
})
export class UserModule {}

import { Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { UserModule } from '../user/user.module';

@Module({
  imports: [UserModule],
  controllers: [AuthController],
  providers: [AuthService],
})
export class AuthModule {}