Skip to content

Commit

Permalink
fix(templates): ensure proper asynchronous initialization of DB conne…
Browse files Browse the repository at this point in the history
…ction pool

The DBConnector class constructor was calling an asynchronous function, leading to potential errors when the pool was not fully initialized before being used. This fix moves the asynchronous pool creation to a separate init method, ensuring the pool is ready before any connections are attempted.

Closes #89
  • Loading branch information
JuanVillegas95 authored and LeonSilva15 committed Jul 26, 2024
1 parent eb8a245 commit fa8009e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 13 deletions.
42 changes: 30 additions & 12 deletions templates/app/utils/db/index.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,38 @@ oracledb.autoCommit = true;

class DBConnector {
constructor() {
this.pool = oracledb.createPool({
...dbConfig,
poolMax: 10,
poolMin: 10
});
this.pool = null;
}

getConnection(options = {}) {
const pool = oracledb.getPool();
return pool.getConnection({
...dbConfig,
...options
});
async init() {
try {
this.pool = await oracledb.createPool({
...dbConfig,
poolMax: 10,
poolMin: 10
});
console.log('Connection pool created successfully.');
} catch (error) {
console.error('Error creating connection pool:', error);
throw error;
}
}

async getConnection(options = {}) {
if (!this.pool) {
throw new Error('Connection pool not initialized.');
}
try {
const connection = await this.pool.getConnection({
...dbConfig,
...options
});
return connection;
} catch (error) {
console.error('Error getting connection:', error);
throw error;
}
}
}

module.exports = new DBConnector();
module.exports = new DBConnector();
3 changes: 2 additions & 1 deletion templates/app/utils/rest-services/connection.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@
const db = require( '../db/index.cjs' );

exports.getStatus = async function () {
await db.init();
const connection = await db.getConnection();
const result = await connection.execute( 'select 1 from dual' );
await connection.close();

return {
status: 'ok',
}
};
};

0 comments on commit fa8009e

Please sign in to comment.