Node-restify: Middleware for specific route

Created on 19 Apr 2016  路  4Comments  路  Source: restify/node-restify

How to build a middleware for a specific route like in express?

Should I use promises?

I want to do something like this:

var mid = function(req, res, next) {
  models.Team.find({
      where: {
        id: req.params.id
      }
    }).then(team => {
      if (team) {
        req.team = team;
        return next();
      } else {
        res.send(404, 'Team not found');
      }
    }).catch(err => {
      send(500, err);
    });
};


// -----------------------------------------------

var getById = function(req, res, next) {
  mid(req, res, next);
  res.send(req.team);
  return next();
};

Most helpful comment

If getById is your specific route, you'll want to add your handler as part of a chain when you mount your route:

server.get('/foo/:id', [mid, getById]);

This ensures that your mid middleware runs to completion before it calls the next handler (in this case getById).

All 4 comments

If getById is your specific route, you'll want to add your handler as part of a chain when you mount your route:

server.get('/foo/:id', [mid, getById]);

This ensures that your mid middleware runs to completion before it calls the next handler (in this case getById).

@micahr
What about the middleware function?
Is that the right way to retrieve data from database?
Is there any way to send an error from the middleware? If so, should I do it?

Thanks a lot for your fast reply.

The way you retrieve data from your database is not something I can help with too much, as that is very specific to your application. The way you are doing it seems fine from the sense of catching any errors and sending a 500 error to the client.

@augustovictor Looks like we're good here, let us know if you have other questions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

FLYBYME picture FLYBYME  路  6Comments

sloncho picture sloncho  路  3Comments

0v3rst33r picture 0v3rst33r  路  6Comments

mikemilano picture mikemilano  路  4Comments

sonnyp picture sonnyp  路  7Comments