Skip to content

Commit a87eab5

Browse files
author
Miroslav Bajtoš
committed
Move context example to a standalone app
1 parent 598bb24 commit a87eab5

File tree

3 files changed

+30
-5
lines changed

3 files changed

+30
-5
lines changed

example/client-server/models.js

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,6 @@ CartItem.sum = function(cartId, callback) {
1818
return prev + cur;
1919
}, 0);
2020

21-
var ns = loopback.getCurrentContext();
22-
if (ns && ns.get('http')) {
23-
console.log('Remote call via url: %s', ns.get('http').req.url);
24-
}
2521
callback(null, total);
2622
});
2723
}

example/client-server/server.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ var memory = loopback.createDataSource({
55
connector: loopback.Memory
66
});
77

8-
server.use(loopback.rest({context: {enableHttpContext: true}}));
8+
server.use(loopback.rest());
99
server.model(CartItem);
1010

1111
CartItem.attachTo(memory);

example/context/app.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
var loopback = require('../../');
2+
var app = loopback();
3+
4+
// Create a LoopBack context for all requests
5+
app.use(loopback.context());
6+
7+
// Store a request property in the context
8+
app.use(function saveHostToContext(req, res, next) {
9+
var ns = loopback.getCurrentContext();
10+
ns.set('host', req.host);
11+
next();
12+
});
13+
14+
app.use(loopback.rest());
15+
16+
var Color = loopback.createModel('color', { 'name': String });
17+
Color.beforeRemote('**', function (ctx, unused, next) {
18+
// Inside LoopBack code, you can read the property from the context
19+
var ns = loopback.getCurrentContext();
20+
console.log('Request to host', ns && ns.get('host'));
21+
next();
22+
});
23+
24+
app.dataSource('db', { connector: 'memory' });
25+
app.model(Color, { dataSource: 'db' });
26+
27+
app.listen(3000, function() {
28+
console.log('A list of colors is available at http://localhost:3000/colors');
29+
});

0 commit comments

Comments
 (0)