1
I have this class I use to create the connection:
class DbConnection {
constructor() {
this._con = undefined;
this._pool = undefined;
}
_createPool( database , user, password ) {
this._pool = mysql.createPool({
connectionLimit: 100,
host: "localhost",
port: 3306,
database: database,
user: user,
password: password
});
}
async openConnection( req ) {
this._createPool(req.database, req.user, req.password );
return new Promise((resolve, reject) => {
this._pool.getConnection((err, connection) => {
if (err)
reject( err );
this._con = connection;
resolve();
});
});
}
async beginTransaction() {
return new Promise((resolve, reject) => {
this.con.beginTransaction(err => {
if (err) {
this.con.rollback( () => this.con.release() );
reject( err );
}
resolve();
});
});
}
get con() {
return this._con;
}
close() {
if (this.con)
this.con.release();
}
}
This is the control:
class GenericCtrl {
constructor( db, dao ) {
this._db = db;
this._dao = dao;
}
async buscar( req, res ) {
req.assert( 'id', 'um id é necessário.' ).notEmpty().isInt().withMessage('Deve ser inteiro');
if (req.validationErrors())
return res.status( 400 ).json( { erros: req.validationErrors() } );
try {
await this._db.openConnection( req );
let response = await this._dao.read( req.params.id );
res.status( 200 ).json( response );
} catch (e) {
res.status( 500 ).json( { erro: e.toString() } );
} finally {
this._db.close();
}
}
}
This is the DAO:
class GenericDao {
constructor( db ) {
this._db = db;
}
get con() {
return this._db.con;
}
read( query, sql = undefined, inserts = undefined ) {
sql = "SELECT * FROM ?? WHERE ?? = ?";
inserts = [ 'Usuario', 'id', 23 ];
sql = mysql.format(sql, inserts);
return new Promise( ( resolve, reject ) => {
this.con.query( sql, ( err, result ) => err ? reject( err ) : resolve( result ) );
});
}
}
It has more Code, I just removed the part that I think necessary for the issue.
The code works, but sometimes it shows an error in the log
as the message:
Unhandledpromiserejectionwarning: Error: Connection already Released
I don’t know how to fix this. Can anyone help me? If you need more details I will update the question. Thanks in advance!
Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).
– Sorack