From 30218be9e56e589fe5cb50c110420eb763276ab5 Mon Sep 17 00:00:00 2001 From: Amir Jafarian Date: Wed, 23 Nov 2016 18:11:45 -0500 Subject: [PATCH] Add app using loopback-context --- example/app.js | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 example/app.js diff --git a/example/app.js b/example/app.js new file mode 100644 index 0000000..6214757 --- /dev/null +++ b/example/app.js @@ -0,0 +1,43 @@ +// Copyright IBM Corp. 2014,2016. All Rights Reserved. +// Node module: loopback-context +// This file is licensed under the MIT License. +// License text available at https://opensource.org/licenses/MIT + +'use strict'; + +var contextPerRequest = require('../server/middleware/per-request.js'); +// Use `var lbContext = require('loopback-context');` in your app +var lbContext = require('../'); +var loopback = require('loopback'); + +var app = loopback(); + +// Configure the context middleware +app.middleware('initial', contextPerRequest()); + +// Store a request property in the context +app.use(function saveHostToContext(req, res, next) { + var currentContext = lbContext.getCurrentContext(); + if (currentContext) + currentContext.set('host', req.hostname); + 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 currentContext = lbContext.getCurrentContext(); + if (currentContext) + console.log('Request to host %s', + currentContext && currentContext.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'); +});