othiym23 / node-continuation-local-storage

implementation of https://github.com/joyent/node/issues/5243
BSD 2-Clause "Simplified" License
1.13k stars 207 forks source link

Koa NameSpace lost after using Knex #49

Closed NekrasovEV closed 8 years ago

NekrasovEV commented 8 years ago
'use strict'
let koa = require('koa');
let cls = require('continuation-local-storage');
let nameSpace = cls.createNamespace('app.context');
var knex = require('knex')({
      "client": "mysql",
      "connection":{
            "host": "localhost",
            "user": "test",
            "password": "123",
            "database": "testBase",
            "port": "3006"
        },
      "pool":{"min":1, "max":200}  
    });

var app = koa();

app.use(function*(next){
    yield new Promise(nameSpace.bind(function (resolve) {
        resolve();
    }));
    nameSpace.set('token', 123);
    yield next;         
})

app.use(function * () {
    let token;
    token = cls.getNamespace('app.context').get('token');
    console.log(token);
    //123
    yield knex.select(knex.raw('1'));  
    token = cls.getNamespace('app.context').get('token');
    //undefined
    console.log(token);

});

app.listen(3000);
NekrasovEV commented 8 years ago

I replaced this code

app.use(function*(next){
    yield new Promise(nameSpace.bind(function (resolve) {
        resolve();
    }));
    nameSpace.set('token', 123);
    yield next;         
})

it works

app.use(function*(next){
    let context = nameSpace.createContext();
    nameSpace.enter(context);
    try {
        nameSpace.set('token', 123);
        yield next;
    }
    finally {
        nameSpace.exit(context);
     }        
})