MathieuAuclair
MathieuAuclair

Reputation: 1337

How to get a function of parent object (module NodeJS)

I'm working on a nodejs module that will handle all my SQL stuff for a project, and I have a problem with the language, there's no parent relation in javascript and I can't duplicate my connection or I will get a handshake error, so how do I make a reference toward this.connection without instantiating the setup object.

I know that this question might be a bit wide, but if anyone has a solution or an idea to get around that problem, I would like to hear it, so feel free to propose stuff!

here's my current code :

require("dotenv").config();
const mysql = require("mysql");
const sqlstring = require("sqlstring");

function setup(){
    this.connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password : process.env.PASSWORD,
        database : 'DISCORD'
    }), 
    this.connect = function(){
        this.connection.connect(function(err){
            if(err){
                throw err;
            }
        });
    },
    this.makeRequest = function(requestName, param){
        this.connection.query("SELECT SQLQUERY FROM QUERYLIST WHERE NAME = " + this.formatString(requestName),function(err, result){
            if(err){
                throw err;
            } else{
                 //-------- CAN'T CALL THIS NOT IN SETUP OBJECT ANYMORE
                this.connection.query(result[0].SQLQUERY + this.formatString(param), function(err2, result2){
                    return result2;
                });
            }
        });
    },
    this.formatString = function(string){
        return sqlstring.escape(string);    
    }
}

I tought about making something like this but it didn't work...

this.makeRequest = function(requestName, param){
    this.connection.query(result[0].SQLQUERY + this.formatString(param),this.test);
},
this.test = function(err, result){
    //stuff
}

Upvotes: 0

Views: 200

Answers (1)

GabLeRoux
GabLeRoux

Reputation: 17973

I think that what you're looking for is to reuse your mysql connection across your different modules. There is this similar question that shows how to do so: How to properly pass mysql connection to routes with express.js

Make sure you setup your mysql connection once and let everything else reuse this connection. In other words, make a singleton out of it using Pool variable as shown in the first answer.

Upvotes: 1

Related Questions