Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 209
user3537411 Avatar asked Dec 06 '15 03:12

user3537411


1 Answers

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.

like image 135
Saad Avatar answered Oct 16 '22 17:10

Saad