2016-07-29 07:29:10 +00:00
|
|
|
# loopback-context
|
2016-07-28 13:11:12 +00:00
|
|
|
|
|
|
|
Current context for LoopBack applications, based on
|
|
|
|
node-continuation-local-storage.
|
2016-07-28 13:40:19 +00:00
|
|
|
|
2016-08-01 13:20:11 +00:00
|
|
|
## WARNING
|
|
|
|
|
2016-08-10 12:16:21 +00:00
|
|
|
**We recommend AGAINST using the loopback-context module until there is a stable solution to the issue below!**
|
|
|
|
|
2016-08-01 13:20:11 +00:00
|
|
|
The module node-continuation-local-storage is known to have many problems,
|
|
|
|
see e.g. [issue #59](https://github.com/othiym23/node-continuation-local-storage/issues/59).
|
|
|
|
As a result, loopback-context does not work in many situations, as can be
|
|
|
|
seen from issues reported in LoopBack's
|
|
|
|
[issue tracker](https://github.com/strongloop/loopback/issues?utf8=%E2%9C%93&q=is%3Aissue%20getCurrentcontext).
|
|
|
|
|
|
|
|
If you are running on Node v6, you can try the new alternative
|
|
|
|
[cls-hooked](https://github.com/Jeff-Lewis/cls-hooked).
|
|
|
|
|
2016-07-28 13:40:19 +00:00
|
|
|
## Usage
|
|
|
|
|
2016-08-01 13:02:47 +00:00
|
|
|
1) Add `per-request` middleware to your
|
2016-07-28 13:40:19 +00:00
|
|
|
`server/middleware-config.json`:
|
|
|
|
|
|
|
|
```json
|
|
|
|
{
|
|
|
|
"initial": {
|
2016-08-01 13:02:47 +00:00
|
|
|
"loopback-context#per-request": {
|
2016-07-28 13:40:19 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
2) Then you can access the context from your code:
|
|
|
|
|
|
|
|
```js
|
2016-07-29 07:29:10 +00:00
|
|
|
var LoopBackContext = require('loopback-context');
|
2016-07-28 13:40:19 +00:00
|
|
|
|
|
|
|
// ...
|
|
|
|
|
|
|
|
MyModel.myMethod = function(cb) {
|
2016-07-29 07:29:10 +00:00
|
|
|
var ctx = LoopBackContext.getCurrentContext();
|
2016-07-28 13:40:19 +00:00
|
|
|
ctx.get('key');
|
|
|
|
ctx.set('key', { foo: 'bar' });
|
|
|
|
});
|
|
|
|
```
|
|
|
|
|
2016-08-01 13:20:11 +00:00
|
|
|
See the official LoopBack
|
|
|
|
[documentation](https://docs.strongloop.com/display/APIC/Using+current+context)
|
|
|
|
for more details.
|