skonves / express-http-context

Get and set request-scoped context anywhere
MIT License
300 stars 26 forks source link

Context lost after mysql query #15

Open anubhav756 opened 6 years ago

anubhav756 commented 6 years ago

I'm trying to get http context after a mysql query in express app. The context seems to be lost after executing a query:

const app = require('express')();
const httpContext = require('express-http-context');
const connection = require('mysql').createConnection({ ... });

connection.connect();

app.use(httpContext.middleware);

app.get('/', (req, res) => {
    httpContext.set('foo', 'bar');

    console.log(httpContext.get('foo'));      // prints 'bar'

    connection.query('SELECT * FROM some.table', (err, result, fields) => {
        if (err) throw err;

        console.log(httpContext.get('foo'));  // prints undefined!
        ...
    });
});
...

Please help

skonves commented 6 years ago

Thanks for the feedback :+1:

What are the current versions of node, npm, and your operating system?

anubhav756 commented 6 years ago

Ubuntu: 16.04 LTS node: 8.11.3 npm: 5.6.0 express: 4.16.3 express-http-context: 1.0.3 mysql: 2.16.0

Hope that helps :slightly_smiling_face:

Devtronyx commented 6 years ago

Same behaviour for mongoose

osx: 10.14 node: 10.7.0 npm: 6.1.0 express: 4.16.3 express-http-context:1.0.4 mongoose: 5.2.4

ranjithchev commented 6 years ago

Any answers for this??

skonves commented 6 years ago

Thanks @Tzira for the info! 😄

I wrote a more detailed status update in https://github.com/skonves/express-http-context/issues/18

victordidenko commented 5 years ago

Just tested with following:

osx: 10.14.3 node: 11.10.0 yarn: 1.13.0

├─┬ @nestjs/core@5.7.3
│ └── express@4.16.3
├── express-http-context@1.2.0
├── mysql@2.16.0
└── typeorm@0.2.14

looks like context isn't lost after mysql queries, works fine for me 🤓 Also tried to run inside docker node:8.12, also works fine.

I'm not sure, why, though. I use async-await everywhere across my code, mysql is used internally by TypeORM.

zhujun24 commented 5 years ago

Same behaviour for mysql

OS: macOS 10.14.6 / CentOS 7 node: 8.9.4 npm: 6.10.3 express: 4.16.4 express-http-context: 1.2.3 mysql: 2.17.1

But new mysql connection everytime will works :smirk::


app.get('/', (req, res) => {
  const connection = mysql.createConnection({ xxx })
  const connection.connect()
  connection.query(SQL, (err, result, fields) => {
    httpContext.get('xxx') // it will works
  })
})
``
zhujun24 commented 5 years ago

I fixed it with promisify #946

util.promisify(connection.query).bind(connection)('SELECT * FROM some.table')
  .then((result, fields) => {
    console.log(httpContext.get('foo'));  // prints bar
  })
  .catch(error => {});