skonves / express-http-context

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

Return wrong context in promise chain #28

Open tunv-pnc opened 5 years ago

tunv-pnc commented 5 years ago

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!

salmgazer commented 5 years ago

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

rohitsud commented 5 years ago

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.

halu886 commented 5 years ago

@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 commented 5 years ago

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