0

What would be considered a best practice to extend restify with a db object that can be used in every route?

Ideally I would want to do something similar to this express practice.

const app = express();

app.use('/api/users', usersRestApi);

app.get('/', (req, res) => {
  res.send('Hello World');
});

// Create MongoDb connection pool and start the application
// after the database connection is ready
MongoClient.connect(config.database.url, { promiseLibrary: Promise }, (err, db) => {
  if (err) {
    logger.warn(`Failed to connect to the database. ${err.stack}`);
  }
  app.locals.db = db;
  app.listen(config.port, () => {
    logger.info(`Node.js app is listening at http://localhost:${config.port}`);
  });
});
eljefedelrodeodeljefe
  • 6,304
  • 7
  • 29
  • 61
  • Why can't you do the same in restify? – HeadCode Sep 21 '16 at 23:41
  • Because in Express you this locals param of `app` and can access it from `req`. That is not possible for `restify`. FWIW, as a workaround I am now attaching it to the server and pass down the server object to the route, to access the db. – eljefedelrodeodeljefe Sep 22 '16 at 21:41
  • You could also put the DB connection stuff in a module and require it at startup. Then you can require it from any model or place where you need DB access. Since required modules are singletons it would be efficient. – HeadCode Sep 22 '16 at 22:06

0 Answers0