Skip to content

Commit

Permalink
fix: coderabbitai suggestion
Browse files Browse the repository at this point in the history
  • Loading branch information
rahul-rocket committed Oct 18, 2024
1 parent 9d2f066 commit 4068acb
Showing 1 changed file with 37 additions and 24 deletions.
61 changes: 37 additions & 24 deletions api/src/connection/datasource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,53 @@ const env = process.env;

/**
* Retrieves the connection options for TypeORM DataSource or TypeORMModule.
*
* @returns The connection options for TypeORM DataSource or TypeORMModule.
*/
export const dataSourceOptions = (): DataSourceOptions => {
const options: DataSourceOptions = {
type: (env.TR_DB_TYPE as any) || 'mysql',
host: env.TR_DB_HOST || 'localhost',
port: parseInt(env.TR_DB_PORT, 10) || 3306,
username: env.TR_DB_USER || 'root',
password: env.TR_DB_PASSWORD || '',
database: env.TR_DB_DATABASE || 'tr_dev',
charset: 'utf8mb4',
synchronize: false,
logging: false,
entities: ['src/entity/*.entity*'],
migrations: ['src/migrations/*'],
namingStrategy: env.TR_DB_TYPE === 'postgres' ? new SnakeNamingStrategy() : new DefaultNamingStrategy(),
};
return options;
// Safely cast the database type or default to 'mysql'
const dbType = (env.TR_DB_TYPE as any) || 'mysql';

// Parse the port safely with fallback to 3306 if parsing fails
const port = isNaN(parseInt(env.TR_DB_PORT, 10)) ? 3306 : parseInt(env.TR_DB_PORT, 10);

// Base options object using the more generic DataSourceOptions
const options: DataSourceOptions = {
type: dbType,
host: env.TR_DB_HOST || 'localhost',
port,
username: env.TR_DB_USER || 'root',
password: env.TR_DB_PASSWORD || 'root',
database: env.TR_DB_DATABASE || 'tr_dev',
charset: 'utf8mb4',
synchronize: false,
logging: false,
entities: [__dirname + '/../entity/*.entity.{js,ts}'],
migrations: [__dirname + '/../migrations/*.{js,ts}'],
namingStrategy: dbType === 'postgres' ? new SnakeNamingStrategy() : new DefaultNamingStrategy(),
};

return options;
};

/**
* Creates and initializes a TypeORM DataSource instance with the provided configuration options.
*
* @returns Initialized TypeORM DataSource instance.
*/
let dataSource: DataSource;
export const getDataSourceConnection = async (): Promise<DataSource> => {
const dataSource = new DataSource(dataSourceOptions());
if (!dataSource) {
dataSource = new DataSource(dataSourceOptions());
}

try {
if (!dataSource.isInitialized) {
await dataSource.initialize();
}
} catch (error) {
console.error(error?.message);
}
try {
if (!dataSource.isInitialized) {
await dataSource.initialize();
}
} catch (error) {
console.error(`Error initializing database connection: ${error?.message}`);
}

return dataSource;
return dataSource;
};

0 comments on commit 4068acb

Please sign in to comment.