Max Heinritz
Max Heinritz

Reputation: 417

Is there an easy way to retrieve all subclass instances of a base class from NestJS DI container?

This is similar to the question asked here, but it does not have a clear answer:

Get all instances of a paritcular kind of Nestjs service

I'm interested in getting a list of all the instances that extend our "BasePoller" class from the NestJS DI container.

My use case is to trigger gracefully shutdown in parallel in response to SIGTERM rather than relying on the NestJS built-in lifecycle methods, so that I can spin down all the pollers in parallel. More information on that use case here:

Can NestJS lifecycle methods run in parallel rather than in sequence?

I was going to ask as part of that question, but it seemed best as a separate one. Thanks!

Upvotes: 2

Views: 1063

Answers (2)

Max Heinritz
Max Heinritz

Reputation: 417

This is possible with DiscoveryService, as described here:

https://github.com/nestjs/nest/issues/9866#issuecomment-1174689723

Here is an example for my use case.

function getAllPollers(app: NestApplication): BasePoller[] {
  const pollers: BasePoller[] = [];
  app
    .get(DiscoveryService)
    .getProviders()
    .forEach((instanceWrapper) => {
      const { instance } = instanceWrapper;
      if (instance instanceof BasePoller) {
        pollers.push(instance);
      }
    });
  return pollers;
}

Upvotes: 2

omidh
omidh

Reputation: 2822

First fetch all providers then filter them out by instanceof BasePoll.

Upvotes: 1

Related Questions