개발일지

Nest.JS MySQL 연결

index.ys 2023. 8. 16. 14:13

TypeORM으로 데이터베이스 연결

라이브러리 설치

npm i typeorm@0.3.7 @nestjs/typeorm@9.0.0 mysql2

app.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    UsersModule,
    ConfigModule.forRoot({
      //환경변수 파일 지정
      envFilePath: ['.development.env'],
      load: [emailConfig, authConfig],
      //전역으로 설정옵션
      isGlobal: true,
      validationSchema,
    }),
    //AppModule에 TypeOrmModule을 동적 모듈로 가져옴
    TypeOrmModule.forRoot({
    //typeOrmModule이 다루고자 하는 데이터베이스읩 타입 MySQL
      type: 'mysql',
      //연결혈 데이터 베이스의 호스트주소
      host: process.env.DATABASE_HOST, // 'localhost',
      //데이터베이스에서 연결을 위해 열어놓은 포트번호 기본값:3306포트
      port: 3306,
      //데이터베이스에 연결할 유저명과 패스워드
      username: process.env.DATABASE_USERNAME, // 'root',
      password: process.env.DATABASE_PASSWORD, // 'test',
      //연결하과 하는 데이터베이스 스키마 이름
      database: 'test',
      //소스 코드 내에서 TyepORM이 구동될 때 인식하도록 할 엔티티 클래스의 경로
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      //서비스 구동 시 소스 코드 기반으로 데이터베이스 스키마를 동기화할지 여부
      //개발시에는 true 프로덕션 환경에서 true로 지정했을때 데이터베이스의 데이터가 초기화 됨
      synchronize: process.env.DATABASE_SYNCHRONIZE === 'false',
      migrations: [__dirname + '/**/migrations/*.js'],
      migrationsTableName: 'migrations',
    })
  ],
  controllers: [HealthCheckController],
  providers: [DogHealthIndicator],
})
export class AppModule {}

TypeOrmModuleOptions

  • retryAttempts: 연결 시 재시도 횟수, 기본값 10회
  • retryDelay: 재시도 간의 지연 시간, 단위는 ms, 기본값은 3000 (3초)
  • toRetry: 에러가 났을때 연결을 시도할지 판단하는 함수, 콜백으로 받은 인수 err을 이용하여 연결여부를 판단하는 함수 구현
  • autoLoadEntities: 엔티티를 자동 로드할지 여부
  • keepConnectionAlive: 애플리케이션 종료 후 연결을 유지할지 여부
  • verboseRetryLog: 연결을 재시도 할떄 verbose레벨로 에러 메시지를 보여줄지 여부, 로깅에서 verbose메시지는 상세 메시지를 의미

 

import { ModuleMetadata, Provider, Type } from '@nestjs/common';
import { DataSource, DataSourceOptions } from 'typeorm';
export declare type TypeOrmModuleOptions = {
    /**
     * Number of times to retry connecting
     * Default: 10
     */
    retryAttempts?: number;
    /**
     * Delay between connection retry attempts (ms)
     * Default: 3000
     */
    retryDelay?: number;
    /**
     * Function that determines whether the module should
     * attempt to connect upon failure.
     *
     * @param err error that was thrown
     * @returns whether to retry connection or not
     */
    toRetry?: (err: any) => boolean;
    /**
     * If `true`, entities will be loaded automatically.
     */
    autoLoadEntities?: boolean;
    /**
     * If `true`, connection will not be closed on application shutdown.
     * @deprecated
     */
    keepConnectionAlive?: boolean;
    /**
     * If `true`, will show verbose error messages on each connection retry.
     */
    verboseRetryLog?: boolean;
} & Partial<DataSourceOptions>;

Ormconfig.json

  • 데이터 베이스를 연결하는 또다른 방법
  • 루트 디렉터리에 ormconfig.json 파일이 있다면 typeormModule.forRoot()에 옵션 객체를 전달하지 않아도됨
  • ormconfig.json을 루트 디렉터리에 작성하고 데이터베이스와 연결하는 방법은 typeorm 0.3 버전에서는 지원하지 안흠
  • Ormconfig.json으로 연결하는 방식보다는 TypeOrmModule.forRoot에 옵션객체를 전달하여 데이터베이스와 연결하는 것을 권장.