#Refactoring a large project to use nestjs-cls

4 messages · Page 1 of 1 (latest)

rocky reef
#

Hello, I'm in the process of refactoring a large project to use a request-scoped context to pass around information about the "current user". The project is too large to initialize the context everywhere at once.

  1. Is there a best practice for marking which functions/services/modules have context initialized, and which ones don't?

We have a large number of public APIs and cron jobs, where information about the current user is not available, or only identifiable after some business logic.

  1. Is there an ergonomic way to setup custom logic for initializing the request context? The logic in question is generally "Retrieve x entity, check y property, retrieve z entity".

  2. For authenticated requests, the context is being initialized in a middleware. For public APIs, does it make more sense to initialize it in the controller or the service?

slate bough
#

I would really think twice before switching to request-scoped things as it will make your application a bit slower.
Not sure to understand exactly what is the problem, but it looks like an authentication logic problem.

If it is, can't you just create an authentication that matches your needs ?
if authenticated user, then no problem.
If not authenticated user, then try to get the context you need
If nothing can be done, save some state about it.

Save the context on the request and eventually create some decorators to make all things easy to use.

blissful jungle
#

@rocky reef from experience, it it best to let the context initialize everywhere. Whether you populate it with the current user only for some routes/modules is a different concern.

rocky reef
#

Does nestjs-cls make every request-scoped? My understanding was that the service was initialized only once, and would create a closure for each request.