Home > Blockchain >  How to properly inject provider in NestJS?
How to properly inject provider in NestJS?

Time:09-24

I create a Firebase provider like below(without using module file with exports and imports):

@Injectable()
export class FirebaseProvider {

    public app: admin.app.App;

    constructor() {
        this.app = admin.initializeApp(config);
    }
}

and add this provider to providers in AppModule:

providers: [AppService, FirestoreProvider, ClientService],

and in ClientModule:

providers: [CustomersService, FirestoreProvider],

so, now i want to use this provider in my ClientService, so I inject this provider via constructor like below:

    constructor(
        private readonly firestoreProvider: FirestoreProvider,
    ) {}

and now i have a problem, can somone tell me why NestJs inject me this provider more than one time and because of this firebase throw me this error:

The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once. But if you do want to initialize multiple 
apps, pass a second argument to initializeApp() to give each app a unique name.

I initialize this firebase only in this provider, so how to properly use this provider in services across the whole project?

thanks for any help!

CodePudding user response:

I don't think you want to declare your FirestoreProvider in the provider:[] array of a module more than once. Try something like this:

@Module({
  imports: [
    FirestoreModule
  ],
})
export class AppModule{}

Now that you've imported the FirestoreModule, you can use it in any class that is in this AppModule. Example:

@Injectable()
export class FooService {
  constructor(private firestore: FirestoreProvider) {}
}

The key here is to define your provider in its own module, then export it via the exports:[] array, and provide it via the providers:[] array of that module.

import { FirestoreProvider } from './FirestoreProvider'

@Module({
  providers: [ FirestoreProvider ],
  exports: [ FirestoreProvider ],
})
export class FirestoreModule{}
@Injectable()
export class FirestoreProvider {

    public app: admin.app.App;

    constructor() {
        this.app = admin.initializeApp(config);
    }
}
  • Related