1

I'm currently writing a node.js project where I defined and instantiated a rethinkdb variable within the main ES6 class.

My question is what is the best method of sharing the database variable amongst all subsequent project classes without re-instantiating the same variable or making another db connection? A "Global" Variable of such.

Something like this the only way? Anyway to define it as a global?

const db = require('rethinkdb');
db.connect({
                        host: config.db.host,
                        port: config.db.port,
                        authKey: config.db.authkey,
                        ssl: {
                            ca: content
                        }
                    }, function(err, conn) {
                        if(err) {
                            fail(err)
                        } else {
                            success(conn)
                        }


                       });

new ClassName(db);

EDIT:

I could also consider making a DB class where the db variable is a singleton? Is that the best way?

CommonSenseCode
  • 23,522
  • 33
  • 131
  • 186
Zander17
  • 1,894
  • 5
  • 23
  • 31

1 Answers1

0

You can use module.exports, so your db variable must be into that object.

module.exports = {
    db: require("rethinkdb")
}
module.exports.db.connect(...);

By now I forgot if module.exports has a built-in function that runs everytime the module is required by require, but this way it should work fine.

boxHiccup
  • 128
  • 8
  • Why not ES6 modules? – Bergi Apr 02 '16 at 18:58
  • It's easy to translate. Here it is, replace `module.exports = {...}` to `export const db = require("rethinkdb");`. And I'm not sure but, to call `module.exports.connect(...)` you can simply do `db.connect(...);`, in case of ES6 – boxHiccup Apr 02 '16 at 19:09
  • Sure it's easy to translate, it's just that the question is tagged with ES6 so I'd recommend using it in answers :-) – Bergi Apr 02 '16 at 20:13
  • Yeah, sincerely, I didn't noticed that initially. But I noticed that he's using too node.js methods, such as `require(...);`, in ES6 it should be `import ...;` – boxHiccup Apr 02 '16 at 20:20