Skip to content

Commit

Permalink
Added local() function to request + tests
Browse files Browse the repository at this point in the history
  • Loading branch information
coopernurse committed Sep 20, 2010
1 parent f6ba793 commit 7c3dc7a
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
31 changes: 31 additions & 0 deletions lib/express/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,37 @@ http.IncomingMessage.prototype.param = function(name){
}
};

/**
* Gets/Sets a request local variable
*
* To set a value:
* req.local('userId', 'abc123');
*
* To get a value:
* var userId = req.local('userId');
*
* Useful when chaining routes with next()
* The first route handler can set a variable on
* the request, which can be accessed by the next
* route handler. Common use case is authentication
* filters, which can set a 'user' object that can
* be accessed downstream on the request.
*/

http.IncomingMessage.prototype.local = function(name, value) {
if (!this.locals) {
this.locals = {};
}

if (value) {
// set case
this.locals[name] = value;
}
else {
return this.locals[name];
}
};

/**
* Queue flash `msg` of the given `type`.
*
Expand Down
21 changes: 21 additions & 0 deletions test/request.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,29 @@ module.exports = {
res.send('ok');
});

assert.response(app,
{ url: '/' },
{ body: 'ok' });
},

'test #local()': function(assert) {
var app = express.createServer();

app.get('/', function(req, res) {
assert.eql(undefined, req.local('userId'));

req.local('userId', 'abc');
assert.eql('abc', req.local('userId'));

req.local('userId', ['a','b']);
assert.eql(['a','b'], req.local('userId'));

res.send('ok');
});

assert.response(app,
{ url: '/' },
{ body: 'ok' });
}

};

0 comments on commit 7c3dc7a

Please sign in to comment.