본문 바로가기

mysql

TYPESCRIPT - typeorm - snakeCase

커스텀 네이밍 전략 사용하기 (옵션): 만약 일관성 있는 네이밍 규칙을 유지하기 위해 모든 엔티티의 컬럼을 스네이크 케이스로 자동으로 매핑하고 싶다면, 커스텀 네이밍 전략을 사용할 수 있습니다. 이 경우, ormconfig.ts 파일 또는 TypeORM 설정 파일에서 namingStrategy를 설정해주면 됩니다. 

 

// snake-case-naming-strategy.ts

import { DefaultNamingStrategy, NamingStrategyInterface } from 'typeorm';
import { snakeCase } from 'typeorm/util/StringUtils';

export class SnakeCaseNamingStrategy extends DefaultNamingStrategy implements NamingStrategyInterface {
  columnName(propertyName: string, customName: string, embeddedPrefixes: string[]): string {
    return customName || snakeCase(propertyName);
  }
}

 

 

만약 ormConfig.ts가 있다면 

// ormconfig.ts

import { SnakeCaseNamingStrategy } from './snake-case-naming-strategy';

module.exports = {
  // ... 기타 설정 ...
  namingStrategy: new SnakeCaseNamingStrategy(),
};

 

 

저는 Appmodule안에서 선언해줬습니다.

import { SnakeCaseNamingStrategy } from './snake-case-naming-strategy';

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        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_DATABASE'),
        entities: [__dirname + '/**/entities/*.entity.ts'],
        logging: true,
        namingStrategy: new SnakeCaseNamingStrategy(),   //-----------여기에 추가
        synchronize: true,
      }),
    }),
    ConfigModule.forRoot({ isGlobal: true, cache: true }),
  ],
----------------------------------------------
})
export class AppModule {}

'mysql' 카테고리의 다른 글

TYPEORM - nestjs - save FK관련 저장문제 해결  (0) 2023.06.14
TYPEORM - Nestjs - Entity(ONETOMANY, MANYTOONE)  (0) 2023.05.23
unic5n - showRoom 쿼리문  (0) 2023.04.15
LIMIT  (0) 2023.04.06
Sub-query  (0) 2023.04.06