10. Relations in SNS

수원 개발자·2023년 12월 10일
0

NestJS

목록 보기
12/15


id : number
nickname : string
email : string
password : string
role : [RolesEnum.USER, RolesEnum.ADMIN]
의 항목을 가진 UserModel을 만들어 보도록 하겠다.

@Entity()
export class UsersModel {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({
    length: 20,
    unique: true,
  })
    // 1) 최대 길이 20
    // 2) 유일무이한 값이 될 것

  nickname: string;
    // 1) 유일무이한 값이 될 것
  @Column({
    unique: true,
  })
  email: string;

  @Column()
  password: string;

  @Column({
    enum: Object.values(RolesEnum),
    default: RolesEnum.USER,
  })
  role: RolesEnum;

  @OneToMany(() => PostsModel, (post) => post.author)
  posts: PostsModel[];
}


// roles.const.ts
export enum RolesEnum {

  // 관리자 또는 사용자

  ADMIN = 'ADMIN',
  USER = 'USER',
}

UserController는 다음과 같이 구성했다.

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get()
  getUsers() {
    return this.usersService.getAllUsers();
  }

  @Post()
  PostUser(@Body('nickname') nickname: string,
           @Body('email') email: string,
           @Body('password') password: string,
           ) {
    return this.usersService.CreateUser(nickname, email, password);
  }
}

관련 메서드들은 usersService를 통해 만들어주고 이를 컨트롤러에서 사용했다.

import { Injectable } from '@nestjs/common';
import { InjectRepository } from "@nestjs/typeorm";
import { UsersModel } from "./entities/users.entity";
import { Repository } from "typeorm";

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(UsersModel)
    private readonly usersRepository: Repository<UsersModel>,
  ) {}

  async CreateUser(nickname: string, email: string, password: string){
    const user = this.usersRepository.create({
      nickname, email, password,
    });

    const newUser = await this.usersRepository.save(user);

    return newUser;
  }

  async getAllUsers(){
    return this.usersRepository.find();
  }
}

0개의 댓글

관련 채용 정보