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

Return wrong context in promise chain

Open tunv-pnc opened this issue 6 years ago • 4 comments

I'm using express-http-context to store request-id(generate each time new request arrived automatically) and get request-id anytime, anywhere I want. In normal case its working fine but if I get context in promise chain it always return context of the first request. Please help me how to always get context of current request.

Thanks a lot!

tunv-pnc avatar Dec 27 '18 11:12 tunv-pnc

@tunv-pnc , did you find a solution to this? kindly share if you did.

salmgazer avatar May 23 '19 15:05 salmgazer

It is possible that you are using a middleware that is not hooked with a CLS compatible promise library. This is a major drawback in using CLS; you need to know all your dependencies that are called in the promise chain and middlewares support CLS.

rohitsud avatar Jun 12 '19 17:06 rohitsud

@tunv-pnc
hello, I try to do a unit test by supertest,but not find the situation. Can you help to check it? :)

it('middleware set request-id concurrency', function (done) {
	// ARRANGE
	const app = express();

	app.use(httpContext.middleware);

	const mw = (req,res,next)=>{
		httpContext.set("request-id",req.header("request-id"));
		next();
	}
	app.use(mw);
	app.get('/test', async (req, res) => {
		const delay = new Number(req.query.delay);
		await new Promise(resolve => setTimeout(resolve, delay)).then(()=>{
				res.status(200).json({
					value: httpContext.get("request-id")
				});
		});
	});

	const sut = supertest(app);

	const request1 = '1';
	const request2 = '2';

	// ACT
	sut.get('/test').set("request-id",request1).query({ delay: 100}).end((err, res) => {
		// ASSERT
		
		assert.equal(res.body.value, request1);
		done();
	});
	
	sut.get('/test').set("request-id",request2).query({ delay: 50}).end((err, res) => {
		// ASSERT
		assert.equal(res.body.value, request2);
	});

});

image

halu886 avatar Jul 02 '19 12:07 halu886

@skonves Hi,Can I make pull request this unit test to this repository?:)

halu886 avatar Jul 02 '19 12:07 halu886