Erik
Erik

Reputation: 14750

Which is the right way to extend ExpressJS/Response object with custom methods?

At now I do extending of request object via middleware:

function(req, res, next) {
  res.customMethod = function() {

  }
  next();
}

But I think it's not correct due polluting of res.prototype namespace. Does anybody know better approach or maybe expressjs4 already have any approach for this?

Upvotes: 2

Views: 382

Answers (1)

matteo
matteo

Reputation: 1715

You are almost perfect in your approach but as you said is better to avoid polluting the res namespace: to reach your goal you can use the res.locals property which is designed for this reason. What follows is a snippet where I attach to the response object the translator of my application.

app.use(function(req, res, next){

      function Translator (lang) {        
          this.lang = lang ? lang : 'it';

          this.translate = function (sentence) {    
              var d = dictionaries.get;

              var translation = d[this.lang] ? d[this.lang][sentence] : d['it'][sentence];          
              return translation ? translation : sentence;
          };                  
          this.setLang = function (l) {
              this.lang = l;
          };
      };

      res.locals.translator = new Translator();
      next();
});

Upvotes: 3

Related Questions