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