Looking for the best way to set up a NestJS database using a .env file in compliance with legal requirements. The goal is to utilize the @nestjs/config
package to import .env variables and incorporate them into the TypeOrmModule.
It appears that utilizing TypeOrmModule.forRootAsync
is necessary.
The attempt at implementation looks like this:
// app.module.ts
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
TypeOrmModule.forRootAsync({
useClass: TypeOrmConfigService,
}),
...
],
})
export class AppModule {}
Next, there's the TypeOrmConfigService
:
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModuleOptions, TypeOrmOptionsFactory } from '@nestjs/typeorm';
@Module({
imports: [ConfigModule],
})
export class TypeOrmConfigService implements TypeOrmOptionsFactory {
constructor(private configService: ConfigService) {}
createTypeOrmOptions(): TypeOrmModuleOptions {
return {
type: 'mysql',
host: this.configService.get('DATABASE_HOST'),
username: this.configService.get('DATABASE_USERNAME'),
password: this.configService.get('DATABASE_PASSWORD'),
};
}
}
The error message indicates an issue:
Nest can't resolve dependencies of the TypeOrmConfigService (?). Please make sure that the argument at index [0] is available in the TypeOrmCoreModule context.
How can this be resolved? Alternatively, is there an example available that demonstrates the integration of NestJs + TypeOrm + @nestjs/config + .env (storing DATABASE_PASSWORD outside of the repository) + configuration (utilizing npm package config to process config/development.yml, config/production.yml, etc.)?
This seems like a very common requirement, essentially the "hello world" setup for every NestJS project, but combining @nestjs/config and TypeOrm presents challenges.
Update: Switching from @Module
to @Injectable
results in the same error being displayed:
yarn run v1.22.4
$ NODE_ENV=development nodemon
[nodemon] 1.19.0
...
Aborted (core dumped)
[nodemon] app crashed - waiting for file changes before starting...