Reputation:
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?
Upvotes: 4
Views: 4204
Reputation: 1070
This worked for me:
TypeOrmModule.forRoot({
type: "sqlite" as any,
host: "localhost",
database: "./database/sqlite"
})
I spent a whole weekend trying to figure out this issue but got stumped.
Does anybody have a better solution or explanation?
Upvotes: 8
Reputation: 1004
Convert your database type to string like below:
export const DATABASE_TYPE: any = String(process.env.DATABASE_TYPE) || 'postgres';
Upvotes: 2