express-http-context
express-http-context copied to clipboard
Context lost after mysql query
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
Thanks for the feedback :+1:
What are the current versions of node, npm, and your operating system?
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:
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
Any answers for this??
Thanks @Tzira for the info! 😄
I wrote a more detailed status update in https://github.com/skonves/express-http-context/issues/18
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.
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
})
})
``
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 => {});