abonifacio / nestjs-request-context

Helper library for accesing request from singleton services
MIT License
65 stars 8 forks source link

Some doc and better package.json #7

Open ScreamZ opened 2 years ago

ScreamZ commented 2 years ago

Hi,

Thanks for your work, just discovered the new AsyncLocalStorage API, and read a lot about it. This is nice :-)

First I wanted to suggest to add this to package.json as it's a minimum required version (not sure NestJS work below), but in terms of "semantic".

"engines" : { 
    "node" : ">=12.0.0
  }

Also for pure understanding could you give me some information about why this is preferred instead of

Thanks a lot :-)

abonifacio commented 1 year ago

Hi! Good idea about the engine restriction, I'll add it soon. As per the questions

Request scoped service ? https://docs.nestjs.com/fundamentals/injection-scopes#request-provider

NestJS explains this themselves

Using request-scoped providers will have an impact on application performance. While Nest tries to cache as much metadata as possible, it will still have to create an instance of your class on each request. Hence, it will slow down your average response time and overall benchmarking result. Unless a provider must be request-scoped, it is strongly recommended that you use the default singleton scope.

But in my case performance was not the main issue, it was the fact that injecting a request scoped service makes the caller service request scoped too.

Taking the test for example https://github.com/abonifacio/nestjs-request-context/blob/master/test/test.service.ts

By using AsyncLocalStorage I can access the request without the service re initializing, useful for in-memory cache. Whether as if I inject a request scoped service the initialization count will increase with each request.

Or https://docs.nestjs.com/fundamentals/injection-scopes#durable-providers

That seems to be the solution to the problem mentioned above, which was added in version 9 (after I created the library). I haven't spent much time on it but, after a quick look, it seems over complicated to me. But that's my opinion only

VishNu2069 commented 1 year ago

What are the downsides of using AsyncLocalStorage? Will it have memory issues since it might be saving a lot of requests in the AsyncLocalStorage object?

Also how to stable is this usage?