Arsene
Arsene

Reputation: 1067

NestJs TypeORM configuration using env files

I have two .env files like dev.env and staging.env. I am using typeorm as my database ORM. I would like to know how to let typeorm read either of the config file whenever I run the application. Error: No connection options were found in any of configurations file from typeormmodule.

Upvotes: 12

Views: 20687

Answers (2)

Syed Ahamed
Syed Ahamed

Reputation: 1

1) i'm using typeorm to to use migration, but in this case i want to use two different folders for migrations(table structure) and seeds(default data to table)

2) so this is how i resolved this in nestjs with typeorm

// config for typeorm and used for mysql driver also
import { DataSource, DataSourceOptions } from 'typeorm';
import { config } from 'dotenv';
config();
const { MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE, PATH_TO_RUN 
} =
process.env;
export const dbConfig: DataSourceOptions = {
  type: 'mysql',
  host: MYSQL_HOST,
  port: 3306,
  username: MYSQL_USER,
  password: MYSQL_PASSWORD,
  database: MYSQL_DATABASE,
  entities: ['dist/**/*.entity.js'],
  migrations: [`dist/db/${PATH_TO_RUN}/*.js`], // update this path with env
};
export default new DataSource(dbConfig);

3) package.json look like after using cross-env this for typeorm

// DON'T PLACE `cross-env` in build script use it in `typeorm` execution script
script: {
"migration:run": "yarn build && cross-env PATH_TO_RUN=migrations yarn typeorm migration:run -d dist/db/mysql.config.js",
"seed:run": "yarn build && cross-env PATH_TO_RUN=seeds yarn typeorm migration:run -d dist/db/mysql.config.js"
}

4) to run this npm script use this below command

yarn migration:run // to use migrations folder in typeorm

yarn seed:run // to use seeds folder in typeorm

!! Before using Yarn and Cross-env please make sure it is installed !!

npm install --global yarn
yarn add cross-env

Upvotes: 0

Kim Kern
Kim Kern

Reputation: 60347

You can create a ConfigService that reads in the file corresponding to the environment variable NODE_ENV:

1) Set the NODE_ENV variable in your start scripts:

"start:dev": "cross-env NODE_ENV=dev ts-node -r tsconfig-paths/register src/main.ts",
"start:staging": "cross-env NODE_ENV=staging node dist/src/main.js",

2) Read the corresponding .env file in the ConfigService

@Injectable()
export class ConfigService {
  private readonly envConfig: EnvConfig;

  constructor() {
    this.envConfig = dotenv.parse(fs.readFileSync(`${process.env.NODE_ENV}.env`));
  }

  get databaseHost(): string {
    return this.envConfig.DATABASE_HOST;
  }
}

3) Use the ConfigService to set up your database connection:

TypeOrmModule.forRootAsync({
  imports:[ConfigModule],
  useFactory: async (configService: ConfigService) => ({
    type: configService.getDatabase()
    // ...
  }),
  inject: [ConfigService]
}),

Upvotes: 17

Related Questions