Bootstrap nestjs server only after the first API call is succeeded

Viewed 340

I have a SecretsService, which fetches secrets (private keys) from a different server and caches it inside it. It has two functions:

  1. fetchSecrets()
  2. get(key: string)

The get() functions expects the fetchSecrets has been called successfully. What's the best place to call this fetchSecrets() function to prevent the nest js server to boot without getting response from this function.

What I have tried so far:

1. I have tried calling this with async like this, but now I am the one creating the instance of the service, so when NestJs tries to create the instance of this service, the secrets cached in this service object are not accessible by that service instance,

async function bootstrap() {
  await new SecretsService().fetchSecrets();
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  ....
}

2. I have added useFactory in the module imports like this, this works well, but the issue here is there are many modules which are dependent on secretsManager service, and I would have to import every module like this.

@Module({
  imports: [
    FirebaseAdminModule.forRootAsync({
      imports: [SecretsManagerModule],
      inject: [SecretsManagerService],
      useFactory: async (secretsManagerService: SecretsManagerService) => {
        await secretsManagerService.fetchSecrets();
        return {
          credential: admin.credential.cert({
            projectId: secretsService.get('GOOGLE_CLOUD_PROJECT'),
            clientEmail: secretsService.get('CLIENT_EMAIL'),
            privateKey: secretsService.get('PRIVATE_KEY').replace(/\\n/g, '\n'),
          }),
        };
      },
    }),
  ],
  providers: [...services],
  exports: [...services],
})
export class CoreModule {}

My Question - Is there any way where I can put my secretsManager.fetchSecrets() such that nest js bootstraps everything after getting a response from the API and cached response (same service instance) can be injected into the modules when it actually bootstraps the AppModule.

Thanks much in advance!!!

0 Answers
Related