import { ConfigModule, ConfigService } from '@nestjs/config';
// configService를 불러오기
const configService = new ConfigService()
@Module({
imports: [
JwtModule.register({
secret: ConfigService.get<string>('JWT_SECRET'),
signOptions: {
expiresIn: '1h',
},
})
],
providers: [AuthService, LocalStrategy, JwtStrategy],
exports: [AuthService],
})
export class AuthModule {}
ChatGPT를 통해 자세하게 물어봤다.
new ConfigService()
**를 사용하면, NestJS의 DI 시스템에 의해 설정된 ConfigService
인스턴스와는 다르게 새로운 인스턴스가 생성됩니다. 이렇게 생성된 인스턴스는 .env
파일 또는 다른 설정 소스에서 설정을 로드하지 않았습니다.new
키워드를 사용하여 직접 인스턴스를 생성하면, 해당 인스턴스는 NestJS의 생명주기와 연동되지 않습니다. 이는 관련된 모듈이나 의존성 주입의 이점을 누리지 못하게 됩니다.ConfigService
**는 다른 모듈이나 서비스에서 재사용할 수 없습니다. 반면, DI를 사용하면 한 번 초기화된 서비스 인스턴스를 애플리케이션 전반에 걸쳐 재사용할 수 있습니다.→ 즉, NestJS에서는 서비스나 프로바이더를 직접 인스턴스화 하는 대신 DI 시스템을 활용해야 한다. 이를 통해 설정, 초기화 및 다른 의존성들이 올바르게 사용된다.
@Module({
imports: [
UserModule,
PassportModule,
TypeOrmModule.forFeature([User]),
// SecretKey 값과 옵션을 넣을 수 있다.
// registerAsync를 사용하여 configService를 넣어보자.
// useFactory를 사용해서 configService 설정
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
// 왜 configService<string>을 하면 바로 못 읽을까?
// 이렇게 해야 configService를 주입시킬 수 있다.
useFactory: async (configService: ConfigService) => {
return {
secret: configService.get<string>('JWT_SECRET'),
signOptions: {
expiresIn: '1h',
},
};
},
}),
],
providers: [AuthService, LocalStrategy, JwtStrategy],
exports: [AuthService],
})