본문 바로가기

Nodejs/NestJS

[NestJS] TypeORM(MySQL) 설정 Migration 포함 03

mysql typeorm을 살펴봅니다.

yarn add mysql typeorm @nestjs/typeorm typeorm-extension

yarn add nestjs-cls @nestjs-cls/transactional @nestjs-cls/transactional-adapter-typeorm

1. mysql과 typeorm 설치

2. transactional을 위한 의존성 추가

* transactional을 좀 더 살펴보고 싶다면 참고

cls에서 Transactional 사용하기: https://papooch.github.io/nestjs-cls/plugins/available-plugins/transactional

typeorm-transactional 사용하기: https://github.com/Aliheym/typeorm-transactional

 

import { Module } from "@nestjs/common";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { TypeOrmModule } from "@nestjs/typeorm";
import { typeORMConfig } from "./config/ormconfig";
import { ClsModule } from "nestjs-cls";
import { ClsPluginTransactional } from "@nestjs-cls/transactional";
import { TransactionalAdapterTypeOrm } from "@nestjs-cls/transactional-adapter-typeorm";
import { DataSource } from "typeorm";
import { getEnvFilePath } from "./database/data-source";

@Module({
  imports: [
    ConfigModule.forRoot({ envFilePath: getEnvFilePath() }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => {
        return typeORMConfig(config);
      },
    }),
    ClsModule.forRoot({
      plugins: [
        new ClsPluginTransactional({
          imports: [TypeOrmModule],
          adapter: new TransactionalAdapterTypeOrm({ dataSourceToken: DataSource }),
        }),
      ],
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

1. TypeOrmModule을 연결하는데, ConfigModule과 ConfigService를 사용하므로 의존성추가 및 forRootAsync로 추가

** 여기서 중요한점, NestJS는 Module이 import 될 때 순서대로 Import 되지 않는다.

2. Transactional 데코레이션을 사용하기 위해서 Cls 추가

 

fucntion typeORMConfig : https://m.blog.naver.com/fbfbf1/222610452307

import { TypeOrmModuleOptions } from "@nestjs/typeorm";

import { DataSourceOptions } from "typeorm";
import { SeederOptions } from "typeorm-extension";
import { join } from "path";
import { ConfigService } from "@nestjs/config";
export const typeORMConfig = (configService: ConfigService): TypeOrmModuleOptions & SeederOptions & DataSourceOptions => {
  const synchronize = configService.get("NODE_ENV") === "local";
  return {
    type: "mysql",
    host: configService.get("DATABASE_HOST"),
    port: +configService.get("DATABASE_PORT"),
    username: configService.get("DATABASE_USERNAME"),
    password: configService.get("DATABASE_PASSWORD"),
    database: configService.get("DATABASE_NAME"),
    entities: [join(__dirname, "../**/*.entity{.ts,.js}")],
    migrations: [join(__dirname, "./../database/migrations/*{.ts,.js}")],
    seeds: [join(__dirname, "./../database/seeds/*{.ts,.js}")],
    synchronize,
    logging: true,
    extra: {
      connectionLimit: 300,
      charset: "utf8mb4_unicode_ci",
    },
  };
};

* 참고:

 - utf8mb4_unicode_ci와 utf8mb4_general_ci의 차이점 https://sir.kr/pg_tip/17446

 - timezone : Z https://ilikezzi.tistory.com/12

 - entity / migrations / seeds 경로 및 파일 설정 필요


TypeORM Migration을 사용하기 위해 typeORMConfig를 생성하고 data-source.ts를 추가

data-source.ts

import { typeORMConfig } from "src/config/ormconfig";
import { DataSource } from "typeorm";
import { config } from "dotenv";
import { ConfigService } from "@nestjs/config";

export const getEnvFilePath = () => {
  const NODE_ENV = process.env.NODE_ENV;
  return ".env" + (NODE_ENV == "local" ? ".local" : NODE_ENV == "development" ? ".development" : "");
};

config({ path: getEnvFilePath() });
const configService = new ConfigService();
export const dataSource = new DataSource(typeORMConfig(configService));

envFile을 module 호출시, data-source.ts 호출시 사용하므로 함수로 변경

** typeorm migration은 nestjs 기능을 사용하지 않고 직접 호출하므로, config에 envfile을 주입.

 

package.json

{
	...
	"migration:generate": "cross-env NODE_ENV=local ts-node --files -r tsconfig-paths/register ./node_modules/typeorm/cli.js migration:generate src/database/migrations/migrations -d src/database/data-source.ts",
   	"migration:run": "cross-env NODE_ENV=development ts-node --files -r tsconfig-paths/register ./node_modules/typeorm/cli.js migration:run -d src/database/data-source.ts",
	...
}
yarn migration:generate
yarn migration:run

위 명령어를 호출하여 typeorm 마이그레이션 완료

 

 

현재까지 코드 보기: https://github.com/close852/nestjs-toy/tree/03

 

 

반응형