NestJS-인증 구현

pingu·2023년 5월 25일
0

typescript

목록 보기
3/3

로그인 구현

기본 CRUD는 실습을 마쳤고 이제 로그인, 회원가입 인증을 해볼 차례이다.
일단 로그인 구현을 할꺼니까 모듈을 만들어야 한다.

nest g module auth

auth/entity/user.entity.ts 생성

import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";

@Entity({name:'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.service.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 생성

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 생성

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 {}

이제 실행하면 됨

npm run start

???

뭐여 분명 그대로 따라했는데?

문제를 번역돌려보고 검색해보니
TypeORM 0.3 버전 이후에는 @EntityRepository대신 @Repository 데코레이터를 사용하란다.
오래된 코드라 리팩토링이 필요하다는 뜻

일단 @EntityRepository를 사용하는 auth/user.repository.ts를 삭제 ㄱㄱ

그리고 아까 UserRepository사용하던 코드들 싹다 바꿔줘야함

UserRepository를 삭제했으니, 그 자리에 entitiy명(난 User다)으로 바꿔준다

auth/user.service.ts

import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { FindOneOptions, Repository } from "typeorm";
import { UserDTO } from "./dto/user.dto";
import { User } from "./entity/user.entity";

@Injectable()
export class UserService{
    constructor(@InjectRepository(User) private userService: Repository<User>){}

    async findByFields(options: FindOneOptions<UserDTO>): Promise<UserDTO | undefined> {
        return await this.userService.findOne(options);
    }

    async save(userDTO: UserDTO): Promise<UserDTO | undefined> {
        return await this.userService.save(userDTO);
    }
}

생성자 이름도 바꿔주시고
auth/auth.service.ts

import { HttpException, HttpStatus, Injectable } from "@nestjs/common";
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserDTO } from "./dto/user.dto";
import { UserService } from "./user.service";
import { User } from "./entity/user.entity";

@Injectable()
export class AuthService {
    constructor(
        @InjectRepository(User)
        private readonly userService: Repository<User>
    ){}

    async registerNewUser(newUser: UserDTO): Promise<UserDTO> {
        let userFind: UserDTO = await this.userService.findOne({ where: { username: newUser.username } });
        if(userFind){
            throw new HttpException('Username already used!', HttpStatus.BAD_REQUEST);
        }
        return this.userService.save(newUser);
    }
}

auth.service도 마찬가지로 변경 ㄱㄱ
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 { UserService } from './user.service';
import { User } from './entity/user.entity';

@Module({
    imports: [TypeOrmModule.forFeature([User])],
    exports: [TypeOrmModule],
    controllers: [AuthController],
    providers: [AuthService, UserService]
  })
export class AuthModule {}

module에도 UserRepository 빼고 user넣기 ㄱㄱ

이제 진짜 실행하면 됨

npm run start


좋아좋아

?

EntityMetadataNotFoundError: No metadata for "User" was found.
엔티티에 메타데이터가 없다는데...

진짜 이거 때문에 또 뭔 파일 잘못 건드렸나 삽질 오지게 함

근데 ㄹㅇ 별거 아님


app.module에 엔티티 추가해주면 끝임ㅋ

허허허허허허ㅓㅎ허헣

회원가입 정보 잘 들어가는거 확인

profile
코딩공부 리뷰

0개의 댓글