반응형
    
    
    
  
다음은 이 글의 동영상 강의 입니다.
Nest로 로그인 기능을 구현하기 위해 우선적으로 회원 가입을 만들어봅니다.
이 예제의 소스는 아래 사이트에서 받으실 수 있습니다.
https://github.com/CodeGearGit/nest-register-sample
GitHub - CodeGearGit/nest-register-sample
Contribute to CodeGearGit/nest-register-sample development by creating an account on GitHub.
github.com
USER 테이블의 구조는 다음과 같습니다.

auth 모듈을 만듭니다.
nest g module auth
auth/entity/user.entity.ts 를 만듭니다.
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity('user')
export class User{
    @PrimaryGeneratedColumn()
    id: number;
    @Column()
    username: string;
    
    @Column()
    password: string;
}
auth/user.repository.ts 를 만듭니다.
import { EntityRepository, Repository } from "typeorm";
import { User } from "./entity/user.entity";
@EntityRepository(User)
export class UserRepository extends Repository<User>{}
auth/dto/user.dto.ts 를 만듭니다.
export class UserDTO {
    username: string;
    password: string;
}
auth/user.servict.ts 를만듭니다.
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { FindOneOptions } from "typeorm";
import { UserDTO } from "./dto/user.dto";
import { UserRepository } from "./user.repository";
@Injectable()
export class UserService{
    constructor(@InjectRepository(UserRepository) private userRepository: UserRepository){}
    async findByFields(options: FindOneOptions<UserDTO>): Promise<UserDTO | undefined> {
        return await this.userRepository.findOne(options);
    }
    async save(userDTO: UserDTO): Promise<UserDTO | undefined> {
        return await this.userRepository.save(userDTO);
    }
}
auth/auth.service.ts 를 만듭니다.
(nest g service auth)
import { HttpException, HttpStatus, Injectable } from "@nestjs/common";
import { UserDTO } from "./dto/user.dto";
import { UserService } from "./user.service";
@Injectable()
export class AuthService {
    constructor(
        private userService: UserService
    ){}
    async registerNewUser(newUser: UserDTO): Promise<UserDTO> {
        let userFind: UserDTO = await this.userService.findByFields({ where: { username: newUser.username } });
        if(userFind){
            throw new HttpException('Username already used!', HttpStatus.BAD_REQUEST);
        }
        return this.userService.save(newUser);
    }
}
auth/auth.controller.ts를 만듭니다.
(nest g controller auth)
import { Body, Controller, Post, Req } from "@nestjs/common";
import { Response, Request } from 'express';
import { AuthService } from "./auth.service";
import { UserDTO } from "./dto/user.dto";
@Controller('api')
export class AuthController {
    constructor(private authService: AuthService){}
    @Post('/register')
    async registerAccount(@Req() req: Request, @Body() userDTO: UserDTO): Promise<any> {
        return await this.authService.registerNewUser(userDTO);
    }
}
auth/auth.module.ts를 아래와 같이 수정합니다.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { UserRepository } from './user.repository';
import { UserService } from './user.service';
@Module({
    imports: [TypeOrmModule.forFeature([UserRepository])],
    exports: [TypeOrmModule],
    controllers: [AuthController],
    providers: [AuthService, UserService]
  })
export class AuthModule {}
서버를 start 합니다.
npm run start:dev
postman에서 다음과 같이 테스트를 합니다.
POST http://localhost:3000/api/register
Body-raw-JSON
{
    "username": "codegear",
    "password": "1111"
}
실행 결과는 다음과 같습니다.

user 테이블에서도 다음과 같이 확인하실 수 있습니다.

반응형
    
    
    
  'Nestjs 기초 동영상강좌' 카테고리의 다른 글
| NestJS - 13. JWT 토큰 인증 - Guard (2) | 2022.01.31 | 
|---|---|
| NestJS - 12. JWT 토큰 생성 (0) | 2022.01.30 | 
| NestJS - 11. 비밀번호 암호화(bcrypt) (2) | 2022.01.29 | 
| NestJS - 10. 로그인 #1 - 아이디/패스워드 체크 (0) | 2022.01.23 | 
| NestJS - 08.TypeORM으로 MySQL Data 처리하기 (0) | 2022.01.15 | 
| NestJS - 07.미들웨어(Middleware) (0) | 2022.01.02 | 
| NestJS - 06.서비스 만들기 (프로바이더) (0) | 2021.12.24 | 
| NestJS - 05.컨트롤러 만들기 (0) | 2021.12.20 |