Home > Mobile >  How to configure the TyepORM module in NestJS without 'process.env' and values unknown at
How to configure the TyepORM module in NestJS without 'process.env' and values unknown at

Time:10-20

Typical example of the configuration of TypeOrmModule via decorator:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'root',
      database: 'test',
      entities: [],
      autoLoadEntities: true, // Must be only on local development mode
      synchronize: true,
    }),
  ],
})
export class AppModule {}

All settings has been hardcoded. What if we don't know at advance the host, port, environment name on which autoLoadEntities flag depends etc.? "At advance" means "when the static fields and values inside decorators has been resolved, but of course, the picking up of all configuration will done before await NestFactory.create().

import { NestFactory } from "@nestjs/core";
import type { NestExpressApplication } from "@nestjs/platform-express";
import Path from "path";
import { Logger } from "@yamato-daiwa/es-extensions";
import { ConsoleCommandsParser } from "@yamato-daiwa/es-extensions-nodejs";


(async function runApplication(): Promise<void> {

  const configurationFromConsoleCommand: ConsoleCommandsParser.ParsedCommand<ConsoleLineInterface.ParsedArguments> =
      ConsoleCommandsParser.parse(process.argv, ConsoleLineInterface.specification);

  const normalizedConfiguration: NormalizedConfiguration = ConfigurationNormalizer.normalize({
    configurationFromConsoleCommand
  });

  ConfigurationRepresentative.initialize(normalizedConfiguration);

  // The preparing of the configuration is complete

  const nestJS_Application: NestExpressApplication =
      await NestFactory.create<NestExpressApplication>(NestJS_ApplicationRootModule);

  await nestJS_Application.listen(normalizedConfiguration.HTTP_Port);

})().

    catch((error: unknown): void => {
      Logger.logError({
        errorType: "ServerStartingFailedError",
        title: "Server starting failed",
        description: "The error occurred during starting of server",
        occurrenceLocation: "runApplication()",
        caughtError: error
      });
    });

One way is a usage of environment variables (process.env.XXX). However it violates the condition "unknown at advance" and must NOT be the only solution.

CodePudding user response:

type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'root',
      database: 'test',

these properties can not be undefined or unknown you must configure them first

import { ConfigModule, ConfigService } from '@nestjs/config';
@Global()
@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        type: 'postgres',
        host: configService.get('DATABASE_HOST'),
        port: configService.get<number>('DATABASE_PORT'),
        username: configService.get('DATABASE_USER'),
        password: configService.get('DATABASE_PASSWORD'),
        database: configService.get('DATABASE_DB'),
        schema: configService.get('DATABASE_SCHEMA'),
        synchronize: !!configService.get<boolean>('DATABASE_SYNCRONIZE'),
        logging: false, //!!configService.get<boolean>('DATABASE_LOGGING'),
        autoLoadEntities: true,
      }),
      inject: [ConfigService],
    }),
  ],
})
  • Related