Jeff-Lewis / cls-hooked

cls-hooked : CLS using AsynWrap or async_hooks instead of async-listener for node 4.7+

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

No context available - how to use? Node 8.12.0 (and Typescript 3.3)

samjeffress opened this issue · comments

Hi,

I'm trying to get a simple example working, but keep getting an error No context available. ns.run() or ns.bind() must be called first. This is locally in unit tests and deployed.

I've written a test that fails:

const createNamespace = require('cls-hooked').createNamespace
const getNamespace = require('cls-hooked').getNamespace

const sessionName = 'cats'

const namespace = createNamespace(sessionName)
console.log('namespace', namespace)
namespace.set('a', 'value')

describe("logger", () => {
  it("should log values passed into init", () => {
    const session = getNamespace(sessionName)
    const baseObject = session.get('a')
  })
})

the error i'm getting is:

    No context available. ns.run() or ns.bind() must be called first.

       7 | const namespace = createNamespace(sessionName)
       8 | console.log('namespace', namespace)
    >  9 | namespace.set('a', 'value')
         |           ^

and the logged out namespace:

    namespace Namespace {
      name: 'cats',
      active: null,
      _set: [],
      id: -1,
      _contexts: Map {},
      _indent: 0 }

I thought that i was following the example :). I did have a look at context.js, but couldn't see what I was supposed to do - any help would be greatly appreciated.

Sam

@samjeffress You would probably have to update your example, to first setup the context, just as the error is suggesting:

const createNamespace = require('cls-hooked').createNamespace
const getNamespace = require('cls-hooked').getNamespace

const sessionName = 'cats'

const namespace = createNamespace(sessionName)
console.log('namespace', namespace)

function someDeepNestedCallToSet() {
     const session = getNamespace(sessionName);
     session.set('a', 'value')
}

function someDeepNestedCallToGet() {
    const session = getNamespace(sessionName);
    const baseObject = session.get('a')

    console.log('is working: ', baseObject);
}

describe("logger", () => {
  it("should log values passed into init", (done) => {
    const session = getNamespace(sessionName);

    // before get/set on the namespace, we call .run to start the context
    session.run(() => {
      someDeepNestedCallToSet();
      someDeepNestedCallToGet();

      done();
    });
  })
})