Ashraf Atef
Ashraf Atef

Reputation: 309

NestJs runtime injection

I have scinario I implemented before in express app using inversifyjs, I need to implement it using nestjs.

I have services(A, B,C) that implement abstact class(Service Abstract) which inheret from the interface (IService). I need to inject one from above services (A or B or C) based on param in route (/:serviceType). How can I achieve that in nest ?

Upvotes: 2

Views: 2638

Answers (1)

Estus Flask
Estus Flask

Reputation: 222493

It can be function service defined with useFactory that returns A, B or else based on provided argument:

providers: [{
  provide: 'GET_AB',
  useFactory: (a: A, b: B) => {
    return (name) => {
     if (name === 'a')
       return a;
     else if (name === 'b')
       return b;
    };
  },
  inject: [A, B]
}]

Injected GET_AB is a function that is used like aOrB = getAB('a');

Upvotes: 3

Related Questions