What is the best way of handling custom event listeners in an express route.
I'm probably doing it all wrong but here's what I have at the moment:
module.exports = {
get: function(req, res, next) {
MyModel.on('error', function(err) {
res.send(501)
})
MyModel.on('found', function() {
res.send(200)
})
MyModel.on('notFound', function() {
res.send(404)
})
MyModel.findByName(req.params.name);
}
}
I can see this is totally wrong since each event listener will be added on each request.
It also feels wrong to start passing the response object around to facilitate responding when an event is fired.
I could just use callbacks on the findByName method but i really like tying into the event system but i'm just wondering how to handle this situation better.
Don't use event bindings for this, use the callback function:
module.exports = {
get: function(req, res, next) {
MyModel.findByName(req.params.name, function (error, model) {
if (error) {
return res.status(501).send(error);
}
if (!model) {
return res.status(404).send('Not found');
}
res.send(model.toJSON());
});
}
}
To add some clarification based on the comments, your example is using express and mongoose, both by the same original author and both primarily oriented with functional style programming and callbacks. While it is possible to design frameworks to use events, callbacks, or both/either (optional), in these 2 specific cases the library forces you to use callbacks because it doesn't provide events for these particular operations. That's why for express and mongoose for these particular calls, callbacks are the idomatic thing.
Now looking at your example, mongoose does emit some events at the Model class level, but those are not associated with an express request/response and thus are more appropriate for error logging and exception handling and some other specialized use cases outside of basic web application response rendering.
So when I said "don't user event bindings for this", I didn't mean event bindings are never appropriate, just that given your specific code snippet, they are neither supported by the libraries you are using nor idiomatic for this example of a basic make-a-db-query-and-send-back-a-web-page scenario.