Skip to content

Commit 7c71116

Browse files
committed
refactor(database): Refactor database initialization, connection, and error handling; update config and decorators
1 parent 3988b57 commit 7c71116

4 files changed

Lines changed: 22 additions & 10 deletions

File tree

src/app.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,13 @@ import { ServiceProvider } from './service/database/ServiceProvider';
33
import logger from './utils/logger';
44
async function main() {
55
const cop = CopBot.getInstance();
6-
await ServiceProvider.initialize();
6+
const db = await ServiceProvider.initialize();
77
logger.info('initialize Database');
88
await cop.initial();
99
logger.info('initial bot');
10+
process.on('SIGTERM', async () => {
11+
await db.close();
12+
process.exit(0);
13+
});
1014
}
11-
main();
15+
main().catch((error) => console.error('Application error:', error));

src/config/index.ts

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,7 @@ class Config {
2222
const dbName = process.env.DB_NAME!;
2323
const dbPassword = process.env.DB_PASSWORD!;
2424
const dbPort = parseInt(process.env.DB_PORT!, 10);
25-
let dbUrl = process.env.DB_URL!;
26-
if (environment === 'production') {
27-
dbUrl = process.env.DATABASE_URL!;
28-
}
25+
const dbUrl = environment === 'production' ? process.env.DATABASE_URL! : process.env.DB_URL!;
2926
this.token = token;
3027
this.environment = environment;
3128
// Initialize the database configuration

src/database/ConnectionPool.ts

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,13 @@ import Config from '../config';
33
import { Catch } from '../decorators/Catch';
44
export class ConnectionPool {
55
private _pool: Pool;
6+
private _isProduction: 'development' | 'production';
67
constructor() {
78
const connectionString = this.getConnectionString();
9+
this._isProduction = Config.environment;
810
this._pool = new Pool({
911
connectionString,
10-
ssl: { rejectUnauthorized: false },
12+
ssl: this._isProduction === 'production' ? { rejectUnauthorized: false } : false,
1113
});
1214
}
1315
@Catch({
@@ -17,17 +19,20 @@ export class ConnectionPool {
1719
})
1820
async connect(): Promise<void> {
1921
try {
20-
await this._pool.connect();
22+
const client = await this._pool.connect();
23+
client.release(); // Verify and release immediately
2124
} catch (error: any) {
22-
console.log('error:', error.code);
25+
console.error('Database connection error:', error.message);
2326
if (error.code === '3D000') {
2427
console.log(`Database does not exist. Creating database ${Config.database.databaseName}...`);
2528
await this.createDatabase();
2629
await this._pool.end(); // End the current pool connection
2730
const newConnectionString = this.getConnectionString();
2831
this._pool = new Pool({
2932
connectionString: newConnectionString,
33+
ssl: this._isProduction === 'production' ? { rejectUnauthorized: false } : false,
3034
});
35+
console.log('Retrying connection after creating the database...');
3136
await this._pool.connect();
3237
}
3338
}
@@ -46,7 +51,12 @@ export class ConnectionPool {
4651
port,
4752
database: 'postgres',
4853
});
49-
await client.query(`CREATE DATABASE ${databaseName}`);
54+
try {
55+
await client.query(`CREATE DATABASE "${databaseName}"`);
56+
console.log(`Database "${databaseName}" created successfully.`);
57+
} finally {
58+
await client.end();
59+
}
5060
}
5161
private getConnectionString(): string {
5262
const { user, host, databaseName, password, port, url } = Config.database;

src/decorators/Catch.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export function Catch(customResponse?: ErrorResponse) {
2929
if (ctx && typeof ctx.reply === 'function') {
3030
await ctx.reply(errorResponse.message);
3131
}
32+
throw error
3233
}
3334
};
3435

0 commit comments

Comments
 (0)