Nestjs instantiate class of services in useFactory

3k views Asked by At

I was checking one of the nestjs module's source code (nestjs-firebase-admin) and I saw something weird. In this line:

private static createProviders(app: admin.app.App): Provider<any>[] {
  return PROVIDERS.map<Provider>((ProviderService) => ({
    provide: ProviderService,
    // here, instantiate each service class
    useFactory: () => new ProviderService(app),
  }));
}

Why do they instantiate each service class? This should be handled by nest core. As I know we just instantiate plain js classes when wrapping up another native plugin. But these are nestjs services. So we should not instantiate them manually. Any idea?

Note: PROVIDERS defined as (all of them are services):

const PROVIDERS = [
  FirebaseAuthenticationService,
  FirebaseMessagingService,
  FirebaseRemoteConfigService,
  FirebaseDatabaseService,
  FirebaseFirestoreService,
  FirebaseStorageService,
];
1

There are 1 answers

12
Jay McDoniel On BEST ANSWER

When we use useFactory we are telling Nest function should be called when the ProviderService (whatever that injection token may be) is used in the application for injection. It looks like the reason for this is that app is not an immediately injectable value (this can be fixed by making it a custom provider, but I guess the nestjs-firebase-admin team thought this was an easier solution). So instead of having injection errors about not being able to inject app automatically, the firebase-admin team decided to instantiate the providers themselves. This is a perfectly valid approach as well, and the reason things like useFactory exists (though, they could have easily used useValue: new ProviderService(app) and avoided the function all). It's just another way to do things