이 글의 동영상 강좌

Backend의 Nestjs에서 Database(MySQL)를 연결하기 위해 TypeORM을 설정해봅니다.
진행 순서는 다음과 같습니다.

MySQL Schema와 User 생성
MySQL Workbench를 이용해서 Schema와 User를 생성합니다.
- Schema : slider
- User : slider
- Password : 1234
자세한 내용은 이전에 작성한 내용을 참조하시기 바랍니다.
https://codegear.tistory.com/32
데이터베이스기초-02.MySQL-Schema, User, Table 생성하기
이 글의 동영상 강의입니다. https://youtu.be/hOOiqk8Z1gQ MySQL Workbench를 이용하여 가장 기본적인 Schema와 User를 생성하고, User에게 Schema의 권한을 주는법과, Schema에 Table을 생성하는 법을 알아보겠..
codegear.tistory.com
패키지 설치
TypeORM과 MySQL 패키지를 설치합니다.
yarn add @nestjs/typeorm typeorm mysql2
TypeORM 설정
/src/orm.config.ts 파일을 아래와 같이 생성합니다.
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
function ormConfig(): TypeOrmModuleOptions {
  const commonConf = {
    SYNCRONIZE: false,
    ENTITIES: [__dirname + '/domain/*.entity{.ts,.js}'],
    MIGRATIONS: [__dirname + '/migrations/**/*{.ts,.js}'],
    MIGRATIONS_RUN: false,
  };
  return {
    name: 'default',
    type: 'mysql',
    database: process.env.DB_NAME,
    host: process.env.DB_HOST,
    port: Number(process.env.DB_PORT),
    username: process.env.DB_USER,
    password: process.env.DB_PASS,
    logging: true,
    synchronize: commonConf.SYNCRONIZE,
    entities: commonConf.ENTITIES,
    migrations: commonConf.MIGRATIONS,
    migrationsRun: commonConf.MIGRATIONS_RUN,
  };
}
export { ormConfig };
Main Module에 typeorm config 설정 추가
/src/app.module.ts에서 @Module -> imports 아래에 다음 내용을 추가합니다.
....
import { TypeOrmModule } from '@nestjs/typeorm';
import { ormConfig } from './orm.config';
@Module({
    imports: [
    	TypeOrmModule.forRootAsync({ useFactory: ormConfig }),
    ]
....
환경 설정 파일(.env) 생성
orm.config.ts에서 process.env.DB_NAME과 같은 형태로 환경변수를 참조하도록 했습니다.
/.env 파일을 아래와 같이 생성합니다.(.env는 dotenv라고 읽습니다.)
NODE_ENV=local
DB_HOST=localhost
DB_PORT=3306
DB_USER=slider
DB_PASS=1234
DB_NAME=slider
- local db에 설정한데로 값을 입력하면 됩니다.
@nestjs/config 모듈 추가
.env 파일을 사용하기 위해서는 dotenv모듈이 필요합니다.
nestjs에서는 @nestjs/config 모듈을 설치하면 dotenv모듈을 사용할 수 있습니다.
아래와 같이 설치를 합니다.
yarn add @nestjs/config
아래와 같이 main module에 ConfigModule 관련 설정을 추가합니다.
/src/app.module.ts
import { ConfigModule } from '@nestjs/config';
...
@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true
    }),
    ....]
...
로그 확인
이제 application을 실행해봅니다.
yarn start
application이 정상적으로 실행되면 아래와 같은 로그를 확인할 수 있습니다.

Entity 생성
위에서 typeorm 설정 파일의 entity 파일 위치를 아래와 같이 설정했습니다.
ENTITIES: [__dirname + '/domain/*.entity{.ts,.js}'],
따라서 src/domain이라는 폴더를 만들고 entity 파일들을 만들면 됩니다.
/src/domain/user.entity.ts 를 아래와 같이 만듭니다.
import { Column, Entity, PrimaryGeneratedColumn, OneToMany } from 'typeorm';
import {UserAuthority} from "./user-authority.entity";
@Entity('user', { schema: 'slider' })
export class User {
    @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
    id: number;
    @Column('varchar', { name: 'kakao_id', length: 45 })
    kakaoId: string;
    @Column('varchar', { name: 'email', length: 100 })
    email: string;
    @Column('varchar', { name: 'name', nullable: true, length: 45 })
    name: string | null;
    @Column('varchar', { name: 'gender', length: 10 })
    gender: string;
    @Column('varchar', { name: 'phone', length: 20 })
    phone: string;
    @Column('varchar', { name: 'birth', length: 10 })
    birth: string;
    @Column('varchar', { name: 'profile_image', nullable: true, length: 200 })
    profileImage: string | null;
    @Column('timestamp', {
        name: 'created_at',
        nullable: true,
        default: () => 'CURRENT_TIMESTAMP',
    })
    createdAt: Date | null;
    @Column('timestamp', {
        name: 'updated_at',
        nullable: true,
        default: () => 'CURRENT_TIMESTAMP',
    })
    updatedAt: Date | null;
    @OneToMany(() => UserAuthority, (userAuthority) => userAuthority.user, {
        eager: true,
    })
    authorities?: any[];
}
/src/domain/user-authority.entity.ts를 다음과 같이 만듭니다.
import {
  Column,
  Entity,
  JoinColumn,
  ManyToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { User } from './user.entity';
@Entity('user_authority')
export class UserAuthority {
  @PrimaryGeneratedColumn()
  id: number;
  @Column('int', { name: 'user_id' })
  userId: number;
  @Column('varchar',{name: 'authority_name'})
  authorityName: string;
  @ManyToOne(() => User, (user) => user.authorities)
  @JoinColumn({ name: 'user_id', referencedColumnName: 'id' })
  user: User;
}
테이블 자동 생성
orm.config.ts 파일에서 syncronize를 true로 변경합니다.
SYNCRONIZE: true,
Application을 실행합니다.
yarn start
MySQL에 테이블이 생성된 것을 확인할 수 있습니다.

이상으로 TypeORM 설정이 완료되었습니다.
'Nestjs 활용 동영상강좌' 카테고리의 다른 글
| (풀스택) Node(Nest)와 Vue(Nuxt)로 사이트 만들기 - 07.사용자 권한 관리 (0) | 2022.10.15 | 
|---|---|
| (풀스택) Node(Nest)와 Vue(Nuxt)로 사이트 만들기 - 06.Front 로그인 (with Jwt Token) (0) | 2022.10.03 | 
| (풀스택) Node(Nest)와 Vue(Nuxt)로 사이트 만들기 - 05.JWT인증 (0) | 2022.10.01 | 
| (풀스택) Node(Nest)와 Vue(Nuxt)로 사이트 만들기 - 04.카카오 로그인 (2) | 2022.09.24 | 
| (풀스택) Node(Nest)와 Vue(Nuxt)로 사이트 만들기 - 02.프로젝트 생성 및 Repository 연결 (0) | 2022.09.12 | 
| (풀스택) Node(Nest)와 Vue(Nuxt)로 사이트 만들기 - 01.강좌 소개 (0) | 2022.09.11 | 
| 카카오 로그인(REST API)④ - Vue(nuxtjs) + Node(nestjs) (0) | 2022.07.03 | 
| 카카오 로그인(REST API)③ - Vue(nuxtjs) + Node(nestjs) (0) | 2022.07.03 |