Search code examples
javascriptnode.jsnestjstypeormdotenv

pass string variable to 'type' in TypeOrmModuleOptions


I want to setup a database connection for my NestJs app using TypeORM. I have a config file which reads all values from the .env file

import { DotenvConfigOutput, config } from 'dotenv';

const envFound: DotenvConfigOutput = config();

if (!envFound) {
  throw new Error('.env file was not found.');
}

process.env.NODE_ENV = process.env.NODE_ENV || 'development';

export const DATABASE_TYPE: string = process.env.DATABASE_TYPE || 'postgres';
export const DATABASE_USERNAME: string = process.env.DATABASE_USERNAME || 'admin';
export const DATABASE_PASSWORD: string = process.env.DATABASE_PASSWORD || 'myPW';
export const DATABASE_HOST: string = process.env.DATABASE_HOST || 'localhost';
export const DATABASE_PORT: number = Number(process.env.DATABASE_PORT) || 5432;
export const DATABASE_NAME: string = process.env.DATABASE_NAME || 'myDB';
export const DATABASE_SYNCHRONIZE: boolean = Boolean(process.env.DATABASE_SYNCHRONIZE) || true;

I am setting up the connection in the app.module, so on application startup.

import {
  DATABASE_TYPE,
  DATABASE_HOST,
  DATABASE_PORT,
  DATABASE_USERNAME,
  DATABASE_PASSWORD,
  DATABASE_NAME,
  DATABASE_SYNCHRONIZE,
} from './config';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: DATABASE_TYPE,
      host: DATABASE_HOST,
      port: DATABASE_PORT,
      username: DATABASE_USERNAME,
      password: DATABASE_PASSWORD,
      database: DATABASE_NAME,
      entities: [],
      synchronize: DATABASE_SYNCHRONIZE,
    }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

Unfortunately I get this error at the type field

Type 'string' is not assignable to type '"mysql" | "mariadb" | "postgres" | "cockroachdb" | "sqlite" | "mssql" | "oracle" | "cordova" | "nativescript" | "react-native" | "sqljs" | "mongodb" | "aurora-data-api" | "expo"'.ts(2322) MysqlConnectionOptions.d.ts(12, 14): The expected type comes from property 'type' which is declared here on type 'TypeOrmModuleOptions'

I don't want to pass in a hardcoded string like 'postgres' because I want it to keep dynamic. I prefer Postgres but some customers use oracle databases and I have to support MSSQL too.

How can I fix that configuration problem?


Solution

  • Convert your database type to string like below:

       export const DATABASE_TYPE: any = String(process.env.DATABASE_TYPE) || 'postgres';