저장을 습관화
NestJS - TypeORM을 위한 app.module.ts 설정 기록 본문
메모...
@nestjs/typeorm, typeorm, mysql2 패키지가 모두 설치되어 있는 상황일때
- app.module.ts
// 생략...
import { TypeOrmModule } from '@nestjs/typeorm';
import { ChannelChats } from './entities/ChannelChats';
import { ChannelMembers } from './entities/ChannelMembers';
import { Channels } from './entities/Channels';
import { DMs } from './entities/DMs';
import { Mentions } from './entities/Mentions';
import { Users } from './entities/Users';
import { WorkspaceMembers } from './entities/WorkspaceMembers';
import { Workspaces } from './entities/Workspaces';
@Module({
imports: [
// 생략...
TypeOrmModule.forRoot({
type: 'mysql',
host: process.env.DB_HOST,
port: 3306,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
entities: [ // 엔티티 폴더에 있는 내용들
ChannelChats,
ChannelMembers,
Channels,
DMs,
Mentions,
Users,
WorkspaceMembers,
Workspaces,
],
// autoLoadEntities:true,
keepConnectionAlive: true,
synchronize: true,
logging: true,
charset: 'utf8mb4_general_ci',
}),
TypeOrmModule.forFeature([Users]),
],
// 생략...
})
export class AppModule implements NestModule {
// 생략...
}
각 옵션 설명
autoLoadEntities: true,
'entities' 옵션과 배열의 내용을 수작업으로 입력하지 않아도 자동으로 읽어오는 옵션
하단 `TypeOrmModule.forFeature([Users])`이 가동될때 entities 폴더의 내용을 읽어 가져오는 방식
성공한다면 `entities: []` 옵션 자체가 생략이 가능하지만 버그가 발생하는 경우가 잦으므로 주의
keepConnectionAlive: true,
배포 후 의도적으로 서버를 종료하는 경우가 아니라면 계속해서 true 상태로 둘 것
이 옵션이 없거나 false이면 기존에 설정해둔 hot reloading으로 인해서
파일 내용 수정 후 저장할 때마다(서버가 재시작될 때마다) 'TypeORM과 DB 연결이 끊어졌다'는 에러 메세지가 출력됨
synchronize: true,
개발 환경일때만 넣는 옵션
엔티티를 직접 작성하고, 이 내용을 DB로 옮길때 필요함
엔티리를 DB로 옮기는 작업이 완료되었다면 false로 돌릴 것
매번 싱크하면 저장된 데이터가 상실될 위험성이 있음
logging: true,
이름 그대로 로그 남기는 옵션
charset: 'utf8mb4_general_ci',
이모티콘을 사용하기 위한 캐릭터셋
- .env
PORT=/* 사용할 포트 */
DB_HOST=/* aws rds의 주소 */
DB_USERNAME=/* aws rds admin 이름 */
DB_PASSWORD=/* aws rds admin 패스워드 */
DB_DATABASE=/* 사용할 데이터베이스 이름 */
[추가]
app.module.ts/TypeOrmModule에서
`type: 'mysql'` 옵션도 숨길 수 있지 않을까? 싶어서
.env에 아래와 같이 옵션을 추가하고
DB_DIALECT=mysql
app.module.ts도 수정해주었지만
TypeOrmModule.forRoot({
type: process.env.DB_DIALECT,
에러가 나면서 실패
내용은 'string' 형식은 '"mysql" | "mariadb" | "postgres" ....' 형식에 할당할 수 없습니다.
아쉽지만 type: 'mysql' 상태를 유지하기로 함
'공부 > node.js' 카테고리의 다른 글
NestJS TypeORM 연습 기록 - migrations (0) | 2023.11.12 |
---|---|
NestJS TypeORM 연습 기록 - DB 생성, 테이블 생성, seeding(초기 데이터 입력) (0) | 2023.11.12 |
에러 기록 - Could not resolve dependency: @nestjs/typeorm@"*" from the root project (0) | 2023.11.11 |
NestJS - 컨트롤러 constructor에 private readonly를 설정하는 이유 (0) | 2023.11.09 |
NestJS - 인터셉터와 AOP (0) | 2023.11.09 |