0

How can I make these two database collections available to all paths with the extension /auth? (For example: /auth/opentickets, /auth/closedtickets, /auth/editdeveloper) Right now, I would have to do add this to every event handler. Is there a better way?

router.get('/auth', function(req, res) {
    var db = req.db;
    // pull from users collection
    db.users.find({}, function(usererr, userdocs){
        if (usererr){ return usererr}
            // pull from developers collection
        db.developers.find({}, function(deverr, devdocs){
            if (deverr) {return deverr}
            res.render('developer', { title: 'Gizmo Ticket System', developers:devdocs, users:userdocs });
        });    
    });    
});
Stennie
  • 63,885
  • 14
  • 149
  • 175

1 Answers1

1

You could place the logic in a middleware before the routes:

router.use(['/auth', '/auth/*'], function(req, res, next) {
  var db = req.db;

  // pull from users collection
  db.users.find({}, function(usererr, userdocs){
    if (usererr)
      return next(usererr);

    // pull from developers collection
    db.developers.find({}, function(deverr, devdocs){
      if (deverr)
        return next(deverr);

      res.locals.title = 'Gizmo Ticket System';
      res.locals.developers = devdocs;
      res.locals.users = userdocs;
      next();
    });
  });
});

router.get('/auth', function(req, res) {
  res.render('auth-main');
});
router.get('/auth/closedtickets', function(req, res) {
  res.render('auth-closedtickets', { title: res.locals.title + ' - Closed Tickets' });
});
// ...

Or if you want the exact same rendering for all of those paths:

router.get(['/auth', '/auth/*'], function(req, res, next) {
  var db = req.db;

  // pull from users collection
  db.users.find({}, function(usererr, userdocs){
    if (usererr)
      return next(usererr);

    // pull from developers collection
    db.developers.find({}, function(deverr, devdocs){
      if (deverr)
        return next(deverr);

      res.render('developer', {
        title: 'Gizmo Ticket System',
        developers: devdocs,
        users: userdocs
      });
    });
  });
});
mscdex
  • 104,356
  • 15
  • 192
  • 153
  • The first example is returning an error. It says router.use requires a callback function, but got a [object array] –  Jul 04 '14 at 17:28
  • Ah ok. I'd consider that a bug, since you can do it for method-specific routes. – mscdex Jul 04 '14 at 18:38