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();
};
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.
Most helpful comment
If
getByIdis your specific route, you'll want to add your handler as part of a chain when you mount your route:This ensures that your
midmiddleware runs to completion before it calls the next handler (in this casegetById).