I turn to you to see if you can help me, since I am trying to implement a singleton pattern with node, but I have a problem since I can not generate the corresponding connection with instance, if you can guide me in what I have to change or within my code, thank you very much
const mysql = require('mysql');
class Mysql {
constructor() {
if (this.instance) {
return this.instance;
}
this.conexion = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'cerveza',
port: '3306'
});
this.conectarDB();
this.instance = this;
}
static conectarDB() {
this.conexion.connect((err) => {
if (err) {
console.log(err);
return;
}
this.conectado = true;
console.log('Base de datos conectado');
});
}
static ejecutarQuery(query, callback) {
this.instance.conexion.query(query, (err, results, fields) => {
if (err) {
console.log("Error en el query");
console.log(err);
return callback(err);
}
if (results.length === 0) {
callback('El registro solicitado no existe');
} else {
callback(null, results);
}
});
}
}
module.exports = {
Mysql
}