简体   繁体   中英

Nest.js async onModuleInit invalid ordering

I have ServiceA that depends on RedisService .

For ServiceA to be initialized, it requires for RedisService to already have been initialized (ie RedisService.onModuleInit to have been called & awaited)

This is ServiceA definition:


// module config
@Module({
    imports: [RedisModule],
    controllers: [ServiceAController],
    providers: [ServiceAService, RedisService],
})
export class ServiceAModule {}

class ServiceA {
    constructor(
        private readonly redisService: RedisService,
    ) {}

    async onModuleInit(): Promise<void> {
        this.logger.debug('Initializing ServiceA...')
        const client = await this.redisService.getClient()
        // do some stuff with client...
        this.logger.debug('Initialized ServiceA')
    }
}

This is RedisService:

class RedisService {
    constructor(private readonly configService: ConfigService) {}

    async onModuleInit(): Promise<void> {
        ...
        this.logger.log(`Initializing Redis client at ${host}:${port}`)
        this.redis = new Cluster([{ port: port, host: host }], clusterConfig)
    }
}

As you can see, RedisService is also being initialized inside of it's onModuleInit lifecycle method.

What I see in logs:

[Nest] 41  - 01/08/2023, 10:30:19 AM   DEBUG [ServiceA] Initializing ServiceA...
[Nest] 41  - 01/08/2023, 10:30:19 AM     LOG [RedisService] Initializing Redis client at redis1:7000
// and here I get an error thrown from ServiceA.onModuleInit saying that Redis hasn't been initialized

And Nest.js even says "ServiceAModule dependencies initialized" before, but onModuleInit for Redis (which is a dependency) wasn't called yet. Why?

How to ensure onModuleInit execution order?

According to the nest docs:

onModuleInit(): Called once the host module's dependencies have been resolved.

It does not mean dependencies already are initialised.

At this point you cant be sure onModuleInit of Redis service runs before onModuleInit in ServiceA.

On the other hand, it is better to have new Cluster initialisation in your Redis controller to avoid situation when your service has no defined properties

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM