Silver Dragon
Silver Dragon

Reputation: 5560

Node.js database initalization from multiple modules

I have 3 modules in a project: A,B,C; all of them are using Rethinkdb, which requires an async r.connect call upon initialization.

I'm trying to make a call from module A to B from command line; however, despite starting r.connect on require(), B couldn't serve this, because rethinkdb haven't loaded by the time the module A calls.

In what ways might this code be refactored, such that I can actually make sure all initializations are complete before calling B?

I've tried to use closures to pass state around modules; however, due to r.connect only being available as async function, this would take the form of:

r.connect( config.rethinkdb, function(err, connection)  {
    rconn = connection;
    // all module requires
    require("./moduleB")(rconn);
    require("./moduleC")(rconn);

    ...lotsacode...
});

Which feels very wrong. Any better suggestions?

Upvotes: 0

Views: 183

Answers (1)

kureikain
kureikain

Reputation: 2314

You can use promise, and pass the connection around. Something like this

r.connect(config.rethinkdb)
.then(function(connection) {
  //do some stuff here if you want
  initWholeApp(connection)
})

and inside initWholeApp connection, you can put your application code.

You can even simplify it to

r.connect(config.rethinkdb)
.then(initWholeApp)

With initWholeApp is a function that accept an argument as the establish connection.

More than that, you can even run each of query on a connection(just ensure to close the connection) once you are done with that query, or using a RethinkDB connection pool with a driver that support it such as https://github.com/neumino/rethinkdbdash or roll your own.

Upvotes: 1

Related Questions