Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS: How to register transient and per web request providers

I am working on a multi-tenant application using NestJS and offering my API through their GraphQL module. I would like to know how I could tell NestJS to instantiate my providers per web request. According to their documentation providers are singleton by default but I could not find a way to register transient or per request providers.

Let me explain a specific use case for this. In my multi-tenant implementation, I have a database per customer and every time I receive a request in the backend I need to find out for which customer it is so I need to instantiate services with a connection to the right database.

Is this even possible using NestJS?

like image 875
orlaqp Avatar asked Dec 08 '18 04:12

orlaqp


1 Answers

With the release of nest.js 6.0, injection scopes were added. With this, you can choose one of the following three scopes for your providers:

  • SINGLETON: Default behavior. One instance of your provider is used for the whole application
  • TRANSIENT: A dedicated instance of your provider is created for every provider that injects it.
  • REQUEST: For each request, a new provider is created. Caution: This behavior will bubble up in your dependency chain. Example: If UsersController (Singleton) injects UsersService (Singleton) that injects OtherService (Request), then both UsersController and UsersService will automatically become request-scoped.

Usage

Either add it to the @Injectable() decorator:

@Injectable({ scope: Scope.REQUEST })
export class UsersService {}

Or set it for custom providers in your module definition:

{
  provide: 'CACHE_MANAGER',
  useClass: CacheManager,
  scope: Scope.TRANSIENT,
}

Outdated Answer

As you can see in this issue, nestjs does not yet offer a built-in solution for request-scoped providers. But it might do so in the near future:

Once async-hooks feature (it is still experimental in node 10) is stable, we'll think about providing a built-in solution for request-scoped instances.

like image 156
Kim Kern Avatar answered Sep 21 '22 11:09

Kim Kern