Monday, 24 April 2017

NodeJs ES6 class private storage

I'm using ES6 to build by nodejs 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 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 in it, with this 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 ?



via Little squirrel

No comments:

Post a Comment