I'm trying to create an independent module in nestjs
for database connections, the problem is that the actual configuration doesn't get params values.
The actual database.module
file:
import {Module} from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { TypeOrmModule } from "@nestjs/typeorm";
@Module({
imports: [
ConfigModule.forRoot({
envFilePath:".env",
isGlobal:true}),
TypeOrmModule.forRoot({
type:'mysql',
host:process.env.DATABASE_HOST,
port:parseInt(process.env.DATABASE_PORT),
username:process.env.DATABASE_USER,
password:process.env.DATABASE_PASSWORD,
database:process.env.DATABASE,
synchronize:true,
entities:[__dirname+"../../domain/entities/*.entity{.ts,.js}"]
}),
],
exports: [TypeOrmModule]
})
export class DatabaseModule{}
database.module.ts is located in src/infrastructure/database
directory, and in the same directory exists the .env
file with credentials associated to variables described into DatabaseModule
The app.module.ts
file contains:
import { Module } from '@nestjs/common';
import { DatabaseModule } from './infrastructure/database/database.module';
import { UserModule } from './infrastructure/modules/user.module';
@Module({
imports: [
DatabaseModule,
UserModule
],
controllers: [],
providers: [
DatabaseModule,
],
exports:[]
})
export class AppModule {}
Please try this way:
@Module({
imports: [
ConfigModule.forRoot({ envFilePath: `${process.env.NODE_ENV}.env` }),
MongooseModule.forRoot(`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@myhost.net?retryWrites=true&w=majority&db=dbname`, { useNewUrlParser: true, dbName: 'dbname' })
...
})
as you already have used import { ConfigModule } from "@nestjs/config"; Instead of these in your code
imports: [
ConfigModule.forRoot({
envFilePath:".env",
isGlobal:true}),
So the final would be:
imports: [
ConfigModule.forRoot({
envFilePath:`${process.env.NODE_ENV}.env`,
isGlobal:true}),
.... TypeOrm Module (...
Then try to setting the script in your package.json
file this way:
"scripts": {
"start: local": "NODE_ENV=local npm run start"
"start:dev": "NODE_ENV=dev npm run start"
}
Hope it helps!