문제 상황
https://yoonchan1121.tistory.com/147
[Error] [Nest] 9248 ERROR [TypeOrmModule] Unable to connect to the database. Retrying (1)...Error: Access denied for user ''@'lo
문제 상황https://yoonchan1121.tistory.com/146 [Error] [Nest] 18036 ERROR [TypeOrmModule] Unable to connect to the database. Retrying (1)...Error: ER_NOT_SUPPORTED_AUTH_MOD문제 상황현재 백엔드는 typeORM, NestJS, MySQL을 사용해서 구성
yoonchan1121.tistory.com
MySQL에 로그인 되지 않는 문제를 해결한 이후 user.entity.ts에서 import구문을 사용할 수 없다는 에러가 발생했다.
오류 내용을 읽어보니 Cannot use import statement outside a module 즉, 모듈 밖에서는 import 구문을 사용할 수 없다는 것이었다.
해결 방안
해결 방법은 간단했다. typeORM 설정을 바꿔주면 된다.
기존의 코드는 다음과 같았다.
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { ConfigService } from '@nestjs/config';
export const typeOrmConfig = async (
configService: ConfigService,
): Promise<TypeOrmModuleOptions> => {
return {
type: 'mysql',
host: configService.get<string>('DB_HOST'),
port: configService.get<number>('DB_PORT'),
username: configService.get<string>('DB_USERNAME'),
password: configService.get<string>('DB_PASSWORD'),
database: configService.get<string>('DB_DATABASE'),
entities: [__dirname + '/../**/*.entity{.ts,.js}'],
synchronize: configService.get<boolean>('DB_SYNCHRONIZE'),
};
};
이 코드의 문제점은 TypeormModule 구성에서 entities 속성이 올바르게 설정되지 않았기 때문에 발생했다.
대부분의 경우 이 문제는 TypeScript 파일을 Javascript 환경에서 import하려고 시도하기 때문에 발생한다고 한다.
webpack을 사용하지 않는 경우에는 다음과 같이 속성을 설정하여 해결할 수 있다.
import { join } from 'path';
{
entities: [join(__dirname, '**', '*.entity.{ts,js}')]
}
join함수를 path 모듈에서 임포트해와서 위와 같이 작성할 수 있다. 이렇게하면 __dirname이 src 또는 dist로 해결되고, 그에 따라 예상된 ts 또는 js 파일을 찾을 수 있다.
만약 ormconfig.json을 사용한다면 다음과 같이 설정해야 한다.
{
"entities": ["dist/**/*.entity.js"]
}
가장 간단하게는 autoLoadEntities옵션을 사용할 수 있다.
{
autoLoadEntities: true
}
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { ConfigService } from '@nestjs/config';
export const typeOrmConfig = async (
configService: ConfigService,
): Promise<TypeOrmModuleOptions> => {
return {
type: 'mysql',
host: configService.get<string>('DB_HOST'),
port: configService.get<number>('DB_PORT'),
username: configService.get<string>('DB_USERNAME'),
password: configService.get<string>('DB_PASSWORD'),
database: configService.get<string>('DB_DATABASE'),
autoLoadEntities: true,
synchronize: configService.get<boolean>('DB_SYNCHRONIZE'),
};
};
*autoLoadEntities: TypeORM에서 사용되는 옵션으로, 엔티티 클래스를 수동으로 지정하는 대신에 자동으로 모든 엔티티 클래스를 로드하도록 설정하는 옵션이다. 따라서 엔티티 클래스를 명시적으로 배열에 나열할 필요 없이, 프로젝트의 모든 엔티티 클래스를 자동으로 로드해서 사용할 수 있다.
즉, 새로운 엔티티 클래스를 추가하면 해당 클래스가 자동으로 TypeORM에 의해 감지되어 데이터베이스 스키마에 추가된다.