Categories
express javascript node.js

How to add custom function to response object in Node.JS

In my API-application I have a fixed response for errors in different parts. As you can see res.status(400).json({"error": "Invalid input"}) is repeating a lot, in different files and modules actually.

I could create module-function invalidInput(res), which will eliminate duplication, but I really want this to be global part of res object, like res.invalidInput().

How could I make it in JS/Node.JS?

router.get("/users", function(req, res) {
// ...
if (error) {
return res.status(400).json({"error": "Invalid input"});
}
});
router.get("/items", function(req, res) {
// ...
if (error) {
return res.status(400).json({"error": "Invalid input"});
}
});
// etc

You can use your own custom middleware. Add this somewhere above your route handler:

router.use(function(req, res, next) {
res.invalidInput = function() {
return res.status(400).json({"error": "Invalid input"});
};
next();
});

and then you can do res.invalidInput() in your route handlers.