반응형
TypeORM 설치
프로젝트 디렉토리에서 다음 명령어 실행
# mysql용
npm i @nestjs/typeorm typeorm mysql2
app.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { Post } from './post/entities/post.entity';
import { PostModule } from './post/post.module';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: '데이터베이스 아이디',
password: '데이터베이스 비밀번호',
database: 'board',
entities: [Post],
synchronize: true,
}),
PostModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
- imports 속성으로 모듈 사용
- TypeModule.forRoot({..}) : forRoot 함수로 설정된 내용은 모든 모듈에 적용됨! 데이터베이스 접속 정보는 전체 프로젝트에서 다 쓰기 때문에 전역으로 설정했음...
- synchronize : 서버 실행할 때마다 entity 최신 동기화 할지 말지
- 이렇게 설정하면 DB 접속 정보가 코드에 노출이 되는 문제가 있는데... 이를 해결하기 위해 @nestjs/config와 joi라는 패키지를 이용한다.
@nestjs/config와 joi 설치
npm i @nestjs/config joi
@nestjs/config의 경우 nodeJS의 .env와 같은 역할을 한다. Nest.js의 설정 관련 패키지!
joi의 경우 .env 값을 집어넣을 때 환경변수의 스키마(형식)를 강제할 수 있다. 이 스키마를 지키지 않으면 서버가 시작될 수 없게 만들어 줌!
nestjs/config와 joi를 적용한 app.module.ts
import Joi from 'joi';
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { Post } from './post/entities/post.entity';
import { PostModule } from './post/post.module';
const typeOrmModuleOptions = {
useFactory: async (
configService: ConfigService,
): Promise<TypeOrmModuleOptions> => ({
type: 'mysql',
host: configService.get('DB_HOST'),
port: configService.get('DB_PORT'),
username: configService.get('DB_USERNAME'),
password: configService.get('DB_PASSWORD'),
database: configService.get('DB_NAME'),
entities: [Post],
synchronize: configService.get('DB_SYNC'),
logging: true,
}),
inject: [ConfigService],
};
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
validationSchema: Joi.object({
DB_HOST: Joi.string().required(),
DB_PORT: Joi.number().required(),
DB_USERNAME: Joi.string().required(),
DB_PASSWORD: Joi.string().required(),
DB_NAME: Joi.string().required(),
DB_SYNC: Joi.boolean().required(),
}),
}),
TypeOrmModule.forRootAsync(typeOrmModuleOptions),
PostModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
useFactory를 사용하여 동적으로 설정 객체를 생성한다.
반응형
'TIL' 카테고리의 다른 글
| [TypeORM] Entity metadata for Show#dates was not found (0) | 2024.03.12 |
|---|---|
| [TypeORM] TypeORM에서 자동으로 컬럼명이 바뀌는 문제 (0) | 2024.03.12 |
| lodash 라이브러리 함수 정리 (0) | 2024.03.08 |
| JavaScript 기본 문법 : find() (0) | 2024.03.08 |
| 캐시에 대해서 (0) | 2024.03.06 |