Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Merge pull request #27 from jonpacker/master
Fix Request-Level exposure.
  • Loading branch information
tj committed Aug 14, 2012
2 parents a33cbf8 + 581590f commit 1b24427
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 34 deletions.
58 changes: 26 additions & 32 deletions lib/express-expose.js
Expand Up @@ -56,38 +56,6 @@ app.expose = function(obj, namespace, name){
namespace = namespace || exports.namespace;
}

// locals
function locals(req, res) {
var appjs = app.exposed(name)
, resjs = res.exposed(name)
, js = '';

if (appjs || resjs) {
js += '// app: \n' + appjs;
js += '// res: \n' + resjs;
}

res.locals[name] = js;
}

// locals

if (!app._exposed[name]) {
var helpers = {};
app._exposed[name] = true;

// request level
if (req) locals(req, this);

// app level
if (!req) {
app.use(function(req, res, next){
locals(req, res);
next();
});
}
}

// buffer string
if ('string' == typeof obj) {
this.js = this.js || {};
Expand All @@ -106,6 +74,32 @@ app.expose = function(obj, namespace, name){
this.expose('\n');
}

// locals
function locals(req, res) {
var appjs = app.exposed(name)
, resjs = res.exposed(name)
, js = '';

if (appjs || resjs) {
js += '// app: \n' + appjs;
js += '// res: \n' + resjs;
}

res.locals[name] = js;
}

// app level locals
if (!req && !app._exposed[name]) {
app._exposed[name] = true;
app.use(function(req, res, next){
locals(req, res);
next();
});
// request level locals
} else if (req) {
locals(req, this);
}

return this;
};

Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -8,6 +8,7 @@
, "mocha": "*"
, "should": "*"
, "jade": "*"
, "supertest": "*"
}
, "main": "index"
}
34 changes: 32 additions & 2 deletions test/express-expose.test.js
Expand Up @@ -7,7 +7,8 @@ var express = require('express')
, expose = require('../')
, assert = require('assert')
, should = require('should')
, vm = require('vm');
, vm = require('vm')
, request = require('supertest');

module.exports = {
'test app.expose(name)': function(){
Expand Down Expand Up @@ -132,5 +133,34 @@ module.exports = {
vm.runInNewContext(js, scope);
scope.sub(8,7).should.equal(1);
scope.should.not.have.property('add');
}
},

'test res.expose(str)': function(done){
var app = express();
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');

app.expose('var user = { name: "tj" };')
app.expose('user.id = 50;')

app.get('/', function(req, res) {
res.expose('var lang = "en";');
res.expose('var country = "no";');
res.render('index');
});

request(app)
.get('/')
.end(function(err, res) {
if (err) throw err;

var scope = {};
vm.runInNewContext(res.text, scope);
scope.user.name.should.equal('tj');
scope.user.id.should.equal(50);
scope.country.should.equal('no');
scope.lang.should.equal('en');
done();
});
},
};

0 comments on commit 1b24427

Please sign in to comment.