skonves / express-http-context

Get and set request-scoped context anywhere
MIT License
302 stars 27 forks source link

Context undefined when used with routing-controllers #32

Open davidpablosg opened 5 years ago

davidpablosg commented 5 years ago

I've configured the context on ExpressJs app as a dependency on startup and also set it up as global middleware for every request. The code works like a charm when using routing-controllers for Get, Put and Post But, using @Body decorator into a PUT/POST method, it becomes undefined. Also using body-parser, injecting decorator @json, the context get lost.

Working cases:

@Get('/data') public getData():Promise { httpContext.get('contextId');//Got data return new Promise; }

@Get('/data') public getData(@Req() req):Promise { httpContext.get('contextId');//Got data var a = req.a; return new Promise((resolve) => getData(a){ resolve(response); }); }

@Post('/data') public setData():Promise { httpContext.get('contextId'); //Got data var a = 'some random data'; return new Promise((resolve) => setData(a){ resolve(response); }); }

@Post('/data') public setData(@Req() req):Promise { httpContext.get('contextId'); //Got undefined var a = req.a; return new Promise((resolve) => setData(a){ resolve(response); }); }

Not working cases:

@UseBefore(json()) @Post('/data') public setData(@Req() req):Promise { httpContext.get('contextId'); //Got undefined var a = req.a; return new Promise((resolve) => setData(a){ resolve(response); }); }

@Post('/data') public setData(@Body() data):Promise { httpContext.get('contextId'); //Got undefined return new Promise((resolve) => setData(data){ resolve(response); }); }

@Put('/data') public setData(@Body() data):Promise { httpContext.get('contextId'); //Got undefined return new Promise((resolve) => setData(data){ resolve(response); }); }

jungssunkim commented 5 years ago

@davidpablosg It may be a different problem. httpContext middleware must use after body-parser.

reference: https://github.com/skonves/express-http-context/issues/4

zhujun24 commented 4 years ago

I have write a tidy npm package http-request-context to do this, using async_hooks, u can try it.