mardi 26 janvier 2021

Can you use the `useFactory` property in the Angular / NestJS Module Provider and return a Class instead of an instance?

I am using NestJS to build an API. I have a Gateway service to a 3rd-party API that decouples the HTTP calls from the data processing logic. Since I don't want to make requests to the API during development, I use a factory function that returns a Gateway class depending on the environment—TinkMockGateway or TinkGateway.

In the factory function I return the class instead of instances and it works. This is surprising because my implementation differs from the Angular / NestJS documentation. In both documentations [1, 2], they say that you must return an instance of the class you want to inject—which makes sense if we follow the Factory Pattern.

But, when I use the factory function below (NestJS), the dependency is injected correctly (the gateway) depending on the environment.

// other module providers...
{
  provide: TinkGateway,
  useFactory: () => environment.mockTinkGateway ? TinkMockGateway : TinkGateway,
}

Is the framework creating the instances for me or what is going on?

Aucun commentaire:

Enregistrer un commentaire