express-http-context icon indicating copy to clipboard operation
express-http-context copied to clipboard

Context lost after mysql query

Open anubhav756 opened this issue 7 years ago • 8 comments

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

anubhav756 avatar Jul 23 '18 11:07 anubhav756

Thanks for the feedback :+1:

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

skonves avatar Jul 23 '18 15:07 skonves

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:

anubhav756 avatar Jul 23 '18 16:07 anubhav756

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

Devtronyx avatar Aug 08 '18 13:08 Devtronyx

Any answers for this??

ranjithchev avatar Aug 08 '18 17:08 ranjithchev

Thanks @Tzira for the info! 😄

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

skonves avatar Aug 08 '18 18:08 skonves

Just tested with following:

osx: 10.14.3 node: 11.10.0 yarn: 1.13.0

├─┬ @nestjs/[email protected]
│ └── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

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.

victordidenko avatar Feb 26 '19 11:02 victordidenko

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 avatar Aug 21 '19 07:08 zhujun24

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 => {});

zhujun24 avatar Aug 23 '19 02:08 zhujun24