Problem with singleton pattern Nodejs and MySql

1

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
}

    
asked by Edgardo_Valpo 08.10.2018 в 05:22
source

0 answers