Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How add new method in response and request

I want to add new method in response and request of node.js.

How i can do it more efficiently?

I can't understand how this is done in express.js

like image 231
user2417329 Avatar asked Sep 15 '13 19:09

user2417329


1 Answers

Being JavaScript, there are numerous ways to do this. The pattern that seems most reasonable to me for express is to add the function to each request instance in an early middleware:

//just an example
function getBrowser() {
    return this.get('User-Agent'); 
}

app.use(function (req, res, next) {
  req.getBrowser = getBrowser;
  next();
});

app.get('/', function (req, res) {
    //you can call req.getBrowser() here
});

In express.js, this is done by adding additional function to the prototype of http.IncomingMessage.

https://github.com/visionmedia/express/blob/5638a4fc624510ad0be27ca2c2a02fcf89c1d334/lib/request.js#L18

This is sometimes called "monkey patching" or "freedom patching". Opinions vary on whether this is fantastic or terrible. My approach above is more prudent and less likely to cause intended interference with other code running inside your node.js process. To add your own:

var http = require('http');
http.IncomingMessage.prototype.getBrowser = getBrowser; //your custom method
like image 97
Peter Lyons Avatar answered Nov 10 '22 20:11

Peter Lyons