코딩캠프/내일배움캠프

[ TIL ] 02.21(화) 70일차

고랑E 2023. 2. 21. 21:00
728x90

Nest.js 심화

 

1. 회원가입 / 로그인 기능 구현

 

강의 자료나 영상에서는 src 디렉토리로 이동한 뒤에 실행 하라고 하는데

이게 맥이랑 윈도우 차이인지 src 디렉토리가 아니더라도 잘 생성해주니 그냥 실행한다.

 

User 모듈 / 서비스 추가

nest g mo user
nest g s user

 

user.entity.ts

import {
  Column,
  CreateDateColumn,
  DeleteDateColumn,
  Entity,
  Index,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from "typeorm";

@Entity({ schema: "board", name: "users" })
export class User {
  @PrimaryGeneratedColumn({ type: "int", name: "id" })
  id: number;

  @Index({ unique: true })
  @Column()
  userId: string;

  @Column("varchar", { length: 10 })
  name: string;

  @Column("varchar", { length: 10, select: false })
  password: string;

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date | null;

  @DeleteDateColumn()
  deletedAt: Date | null;
}

 

 

user.service.ts

import {
  Injectable,
  NotFoundException,
  UnauthorizedException,
} from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { InjectRepository } from "@nestjs/typeorm";
import _ from "lodash";
import { Repository } from "typeorm";
import { User } from "./user.entity";

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private userRepository: Repository<User>,
    private jwtService: JwtService
  ) {}

  async login(userId: string, password: string) {
    const user = await this.userRepository.findOne({
      where: { userId, deletedAt: null },
      select: ["id", "password"],
    });

    if (_.isNil(user)) {
      throw new NotFoundException(`User not found. userId: ${userId}`);
    }

    if (user.password !== password) {
      throw new UnauthorizedException(
        `User password is not correct. userId: ${userId}`
      );
    }

    // 뭔가 허전합니다
  }

  async createUser(userId: string, name: string, password: string) {
    const existUser = await this.getUserInfo(userId);
    if (!_.isNil(existUser)) {
      throw new ConflictException(`User already exists. userId: ${userId}`);
    }

    await this.userRepository.insert({
      userId,
      name,
      password,
    });

		// 역시나 뭔가 허전합니다
  }

  updateUser(userId: string, name: string, password: string) {
    this.userRepository.update({ userId }, { name, password });
  }

  async getUserInfo(userId: string) {
    return await this.userRepository.findOne({
      where: { userId, deletedAt: null },
      select: ["name"], // 이외에도 다른 정보들이 필요하면 리턴해주면 됩니다.
    });
  }
}
  • loginUser
    • 유저가 로그인을 시도할 때 사용하는 함수입니다. 아이디에 대한 비밀번호 일치 여부를 확인하고 성공 시 무언가를 해야 됩니다.
  • createUser
    • 회원가입을 하는 함수입니다. 회원가입을 하기 전에 해당 userId로 가입한 회원이 있으면 회원가입을 할 수 없게 제한해야 합니다. 이후에, 회원가입을 성공하면 무언가를 해야 됩니다.
  • updateUser
    • 회원정보를 수정하는 함수입니다. 당연히, 본인의 정보만 수정할 수 있어야겠죠?
  • getUserInfo
    • 다른 회원들의 정보를 확인하는 함수입니다.