I am currently working with NestJS 10 and TypeORM 0.3.17. In my src/config/data-source.ts file, I have the following code snippet...
import * as dotenv from 'dotenv';
import * as dotenvExpand from 'dotenv-expand';
import { DataSource } from 'typeorm';
dotenvExpand.expand(dotenv.config());
export default new DataSource({
type: 'postgres',
host: process.env.DATABASE_HOST,
port: Number(process.env.DATABASE_PORT) || 5432,
database: process.env.DATABASE_NAME,
username: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
entities: ['dist/**/*.entity.js'],
migrations: ['dist/database/migrations/*.js'],
extra: {
charset: 'utf8mb4_unicode_ci',
},
});
I am looking to refactor the configuration by separating the arguments into a variable for export in my src/config/typeorm.ts file, which currently contains duplicate code...
import { ConfigModule, ConfigService } from '@nestjs/config';
import {
TypeOrmModuleAsyncOptions,
TypeOrmModuleOptions,
} from '@nestjs/typeorm';
export const typeOrmAsyncConfig: TypeOrmModuleAsyncOptions = {
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (): Promise<TypeOrmModuleOptions> => {
return {
type: 'postgres',
host: process.env.DATABASE_HOST,
port: Number(process.env.DATABASE_PORT) || 5432,
database: process.env.DATABASE_NAME,
username: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
synchronize: false,
logging: true,
};
},
};
export const typeOrmConfig: TypeOrmModuleOptions = {
type: 'postgres',
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT, 10),
username: process.env.DB_USERNAME,
database: process.env.DB_NAME,
password: process.env.DB_PASSWORD,
entities: ['dist/**/*.entity.js'],
migrations: ['dist/migrations/**/*.js'],
extra: {
charset: 'utf8mb4_unicode_ci',
},
logging: true,
};
However, when I try to refactor my src/config/data-source.ts file in the following way...
export const dsConfig = {
type: 'postgres',
host: process.env.DATABASE_HOST,
port: Number(process.env.DATABASE_PORT) || 5432,
database: process.env.DATABASE_NAME,
username: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
entities: ['dist/**/*.entity.js'],
migrations: ['dist/database/migrations/*.js'],
extra: {
charset: 'utf8mb4_unicode_ci',
},
};
export default new DataSource(dsConfig);
I encounter the error
Argument of type '{ type: string; host: string; port: number; database: string; username: string; password: string; entities: string[]; migrations: string[]; extra: { charset: string; }; }' is not assignable to parameter of type 'DataSourceOptions'.
Type '{ type: string; host: string; port: number; database: string; username: string; password: string; entities: string[]; migrations: string[]; extra: { charset: string; }; }' is missing the following properties from type 'AuroraMysqlConnectionOptions': region, secretArn, resourceArn
While trying to export new DataSource(dsConfig). How can I correctly refactor my data source configuration file?