I'm using ES6 to build by Node.js app class. I want to create a db class, so I did the following :
"use strict"
var ini = require('node-ini');
var mysql = require('mysql');
let _db = new WeakMap();
// Class de base pour la base de donnée
class Db{
constructor () {
ini.parse('../config/settings.ini', function(err,data){
if(err) {
console.log(err);
return;
} else {
_db.set(this, mysql.createConnection({
host : data.database_MYSQL.host,
user : data.database_MYSQL.username,
password : data.database_MYSQL.password,
database : data.database_MYSQL.schema
}));
}
});
}
}
module.exports = Db;
It's the first I'm trying to store a private variable, and I looked on the web for solutions. I found the Weakmap solution that I tried to implement. But the MySQL connection won't store it with the following source code. I have this output :
_db.set(this, mysql.createConnection({
^
TypeError: Invalid value used as weak map key
at WeakMap.set (native)
at D:\supervision\application\class\db.js:15:21
at D:\supervision\application\node_modules\node-ini\node-ini.js:168:12
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:380:3)
So how to deal with it ?
EDIT :
Here is how caller know when it's initialised :
var db;
function instantiateDb(callback){
db = new db_connector();
callback(db);
}
instantiateDb(function(db){
db.connectDatabase();
})