NestJS+typeORM

00_8_3·2021년 1월 8일
2

NestJS+typeORM+PostgreSQL

이전 포스트 Nest, Node의 프레임웍에 이어 NestJS에 DB를 연결 해보도록 하겠습니다.

Nest 명령어

들어가기 앞서 Nest의 기본적인 명령어를 알아 보겠습니다.

$ nest
>>>
      │ name          │ alias       │ description                                  │
      │ application   │ application │ Generate a new application workspace         │
      │ class         │ cl          │ Generate a new class                         │
      │ configuration │ config      │ Generate a CLI configuration file            │
      │ controller    │ co          │ Generate a controller declaration            │
      │ decorator     │ d           │ Generate a custom decorator                  │
      │ filter        │ f           │ Generate a filter declaration                │
      │ gateway       │ ga          │ Generate a gateway declaration               │
      │ guard         │ gu          │ Generate a guard declaration                 │
      │ interceptor   │ in          │ Generate an interceptor declaration          │
      │ interface     │ interface   │ Generate an interface                        │
      │ middleware    │ mi          │ Generate a middleware declaration            │
      │ module        │ mo          │ Generate a module declaration                │
      │ pipe          │ pi          │ Generate a pipe declaration                  │
      │ provider      │ pr          │ Generate a provider declaration              │
      │ resolver      │ r           │ Generate a GraphQL resolver declaration      │
      │ service       │ s           │ Generate a service declaration               │
      │ library       │ lib         │ Generate a new library within a monorepo     │
      │ sub-app       │ app         │ Generate a new application within a monorepo │
      │ resource      │ res         │ Generate a new CRUD resource

nest의 명령어들 중 우리가 가장 많이 사용하는 세가지 이다.

  • module
  • service
  • controller
$ nest generate module 모듈이름 or (nest g mo 모듈이름)
$ nest generate service 서비스이름 or (nest g s 서비스이름)
$ nest generate controller 컨트롤러이름 or (nest g co 컨트롤러이름)

NestJS 프레임웍의 가장 장점 중 하나로 해당 명령어들로 모듈, 서비스, 컨트롤러 또는 다른 것들을 생성할 때 자동으로 적용 시켜준 다는 것입니다.

PostgreSQL 연결하기

패키지 설치

$ npm i @nestjs/typeorm typeorm pg

폴더 구조

일부 파일이 eslint 오류로 빨갛게 보이지만 스크립트 실행에 문제는 없습니다.

DB연결 - orm.config.ts

import { TypeOrmModuleOptions } from '@nestjs/typeorm';
export const config: TypeOrmModuleOptions = {
  type: 'postgres',
  username: 'postgres',
  password: 'root',
  port: 5432, // 1
  host: '127.0.0.1', // 2
  database: 'nest-typeorm', // 3
  synchronize: true, // 4
  entities: ['dist/**/*.entity{.ts,.js}'], // 5
};
  • 1 PostgreSQL의 기본포트 번호, DB설치시 다른 port로 변경가능 하다.
  • 2 localhost 주소, 배포 할 때 변경 해주자
  • 3 DB이름 설정
  • 4 해당 옵션은 스키마가 DB에 동기화 되도록 해준다.
    주의: 배포 후 해당 옵션으로 인해 데이타 손실을 조심 하자.
  • 5 .entity.ts 또는 .entity.js 파일들을 읽어 DB Table에 등록 해준다.

app.module.ts에 orm.config.ts 연결

import { config } from './orm.config';

@Module({
  imports: [TypeOrmModule.forRoot(config), UsersModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

해당 파일의 imports에 TypeOrmModule.forRoot(config) 추가한다.

users 생성

$ nest generate module users
$ nest generate service users
$ nest generate controller users

해당 명령어를 차례대로 입력하면 users 폴더 아래에 모듈, 서비스, 컨트롤러가 생성된다.

실행 시 service, controllerd의 .spec.ts가 같이 생성되는데 Jest 테스팅에 사용 되는 파일이니 지우셔도 됩니다.

entity 생성

entity를 생성 할 때 users폴더 밖에 entity 폴더를 생성해서 따로 관리 해주어도 된다.

base-entity.ts

import { CreateDateColumn, PrimaryGeneratedColumn } from 'typeorm';

export class BaseEntity {
  @PrimaryGeneratedColumn() // 1
  id: number;
  @CreateDateColumn({ nullable: true })
  createdAt: Date;
  @CreateDateColumn({ nullable: true })
  updatedAt: Date;
}
  • 1 PrimaryGeneratedColumn는 SQL의 Primary key이다. 자동으로 index를 증가 시켜준다.
  • 2 nullable이란 몽구스의 required: false와 같다(필수 입력이 아님)

users.entity.ts

import { BaseEntity } from '../base-entity';
import { Column, Entity } from 'typeorm';

@Entity('users')
export class User extends BaseEntity { // 1
  @Column({ type: 'varchar', length: 100, nullable: false })
  name: string;
  @Column({ type: 'varchar', length: 100, nullable: false, unique: true })
  email: string;
}
  • 1 BaseEntity를 상속 받습니다.
  • 2 Type은 SQL의 타입을 말합니다.

테이블 생성 확인

orm.config.ts 파일은 synchronize 속성 때문에 스크립트를 다시 실행 하지 않아도 PostgreSQL DB의 Table에 생성 되는 것을 볼 수 있습니다.

마침

다음 포스트에서는 연결된 DB에 유저를 회원가입, 유저정보 수정, 유저 삭제 등을 해보도록 하겠습니다.

2개의 댓글

comment-user-thumbnail
2021년 1월 15일

base-entity 코드에서 @CreateDateColumn({ nullable: true }) 여기 부분은
CreateDateColumn을 사용해서 type이 생략 된건가요??

1개의 답글