From 7a1a3b85924ab3d5d5be9de94a967ce78f1c445c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20Bajto=C5=A1?= Date: Tue, 4 Nov 2014 11:24:25 +0100 Subject: [PATCH] Move `context` example to a standalone app --- example/client-server/models.js | 4 ---- example/client-server/server.js | 2 +- example/context/app.js | 29 +++++++++++++++++++++++++++++ 3 files changed, 30 insertions(+), 5 deletions(-) create mode 100644 example/context/app.js diff --git a/example/client-server/models.js b/example/client-server/models.js index 60285dd74..34d5c8bac 100644 --- a/example/client-server/models.js +++ b/example/client-server/models.js @@ -18,10 +18,6 @@ CartItem.sum = function(cartId, callback) { return prev + cur; }, 0); - var ns = loopback.getCurrentContext(); - if (ns && ns.get('http')) { - console.log('Remote call via url: %s', ns.get('http').req.url); - } callback(null, total); }); } diff --git a/example/client-server/server.js b/example/client-server/server.js index 706ea093d..7e466a563 100644 --- a/example/client-server/server.js +++ b/example/client-server/server.js @@ -5,7 +5,7 @@ var memory = loopback.createDataSource({ connector: loopback.Memory }); -server.use(loopback.rest({context: {enableHttpContext: true}})); +server.use(loopback.rest()); server.model(CartItem); CartItem.attachTo(memory); diff --git a/example/context/app.js b/example/context/app.js new file mode 100644 index 000000000..12cedc078 --- /dev/null +++ b/example/context/app.js @@ -0,0 +1,29 @@ +var loopback = require('../../'); +var app = loopback(); + +// Create a LoopBack context for all requests +app.use(loopback.context()); + +// Store a request property in the context +app.use(function saveHostToContext(req, res, next) { + var ns = loopback.getCurrentContext(); + ns.set('host', req.host); + next(); +}); + +app.use(loopback.rest()); + +var Color = loopback.createModel('color', { 'name': String }); +Color.beforeRemote('**', function (ctx, unused, next) { + // Inside LoopBack code, you can read the property from the context + var ns = loopback.getCurrentContext(); + console.log('Request to host', ns && ns.get('host')); + next(); +}); + +app.dataSource('db', { connector: 'memory' }); +app.model(Color, { dataSource: 'db' }); + +app.listen(3000, function() { + console.log('A list of colors is available at http://localhost:3000/colors'); +});