proper approach of avoiding circular dependency and forward ref

Viewed 29

I am working on the app that has two websocket gateways, one is streaming data from provider to app while second is streaming data from app to clients. I have following app structure:

  • src
    • modules
      • provider
        • provider.module.ts
        • provider.gateway.ts
      • proxy
        • proxy.module.ts
        • proxy.service.ts
      • clients
        • clients.module.ts
        • clients.gateway.ts

When app was doing one way communication (provider -> proxy -> clients) it was working properly but as soon as i needed to communicate backwards (clients -> proxy -> provider) I bumped into circular dependency errors. The reason being is that I had to import proxy module into clients module and clients module was already imported into proxy module. The same goes between provider and proxy.

enter image description here

To solve this problem i applied fowardRef on module imports and Inject on gateways and services:

provider.module

@Module({
    imports: [forwardRef(() => ProxyModule)],
    providers: [ProviderGateway],
    exports: [ProviderGateway],
})
export class ProviderModule {}

provider.gateway

export class ProviderGateway {
    constructor(
        @Inject(forwardRef(() => ProxyService))
        private proxyService: ProxyService,
    ) {}
}

proxy.module

@Module({
    imports: [
        forwardRef(() => ClientsModule),
        forwardRef(() => ProviderModule),
    ],
    providers: [ProxyService],
    exports: [ProxyService],
})
export class ProxyModule {}

proxy.service

export class ProxyService {
    constructor(
        @Inject(forwardRef(() => ClientsGateway))
        private clientsGateway: ClientsGateway,
        @Inject(forwardRef(() => ProviderGateway))
        private providerGateway: ProviderGateway,
    ) {}
}

clients.module

@Module({
    imports: [forwardRef(() => ProxyModule)],
    providers: [ClientsGateway],
    exports: [ClientsGateway],
})
export class ClientsModule {}

clients.gateway

export class ClientsGateway {
    constructor(
        @Inject(forwardRef(() => ProxyService))
        private proxyService: ProxyService,
    ) {}
}

Is there a better approach to solve this problem to avoid creating circular dependency and fixing it with fowardRef and Inject?

0 Answers
Related