#onModuleInit execution order

3 messages · Page 1 of 1 (latest)

idle tartan
#

Hello,
How can I make sure a specific modules onModuleInit run before some other module? I know I could resort to onApplicationBootstrap method but I want to keep it extensible if start sequence gets longer.

#

The procedures should be as follows:

  1. I seed the database with some config
  2. The worker services take the config and signal they're ready
    But in my case the onModuleInit() calls happen to do step 2 before step 1
#

step 1 looks like this:

@Injectable()
export class SeedService implements OnModuleInit {
  private readonly logger = new Logger(SeedService.name);
  constructor(private readonly modelConfigService: ModelConfigService) {}
  async onModuleInit() {
    this.logger.debug('Starting...');
// seed code

and step 2 looks like this:

@Injectable()
export class OpenaiService implements IAbstractWorker, OnModuleInit {
  private readonly logger = new Logger(OpenaiService.name);

  client: OpenAI;
  modelConfig: ModelConfig;
  ready: boolean;
  status: IWorkerStatus;

  constructor(
    private readonly modelConfigService: ModelConfigService,
    private readonly workersService: WorkersService,
  ) {
    this.client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY! });
    this.ready = false;
    this.setStatus('starting');
  }

  async onModuleInit(): Promise<void> {
    this.logger.log('Registering openai worker');

    this.modelConfig = await this.modelConfigService.findOne('openai');
    if (!this.modelConfig) {
      this.logger.error('Failed to start worker for openai');
      this.setStatus('misconfigured');
      return;
    }
    this.workersService.register('openai', this);
    this.setStatus('idle');
    this.ready = true;
  }

I know I could use onApplicationBootstrap() but I want to keep it extensible, what's the best way to do that?