nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
71.34k stars 7.91k forks source link

Nest Microservices: Custom strategy injection fails when using dynamic configuration (useFactory) #15144

Closed Stormix closed 3 weeks ago

Stormix commented 4 weeks ago

Is there an existing issue for this?

Current behavior

When using dynamic configuration to create a microservice with useFactory, the current implementation of createServer in NestJS does not properly support custom strategies. It assumes that dynamic configuration will only be used with built-in transport strategies (e.g., Transport.TCP) and does not check for a strategy field in the resolved options.

Code causing the issue:

public createServer(config: CompleteMicroserviceOptions) {
  try {
    if ('useFactory' in config) {
      this.microserviceConfig = this.resolveAsyncOptions(config);
    } else {
      this.microserviceConfig = {
        transport: Transport.TCP,
        ...config,
      } as MicroserviceOptions;
    }

    if ('strategy' in config) { // This should also check for a strategy in the async options.
      this.serverInstance = config.strategy as Server;
      return;
    } else {
      this.serverInstance = ServerFactory.create(
        this.microserviceConfig,
      ) as Server;
    }
  } catch (e) {
    this.logger.error(e);
    throw e;
  }
}

Relevant Docs:

Minimum reproduction code

https://stackblitz.com/edit/nestjs-typescript-starter-mndepscp?file=src%2Fcustom.ts

Steps to reproduce

  1. Attempt to create a microservice with a custom strategy using dynamic configuration:
    const app = await NestFactory.createMicroservice<AsyncMicroserviceOptions>(
    AppModule,
    {
    useFactory: (configService: ConfigService) => ({
      strategy: new CustomStrategy(configService.get('HOST')), // Custom logic
    }),
    inject: [ConfigService],
    },
    );
  2. The strategy is ignored because it is not checked after resolving the config.

Expected behavior

After resolving the async config via useFactory, the framework should check if the resulting config includes a strategy and use it accordingly, just like it does for static configurations.

Package

Other package

No response

NestJS version

^11.0.1

Packages versions

"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.2",
"@nestjs/core": "^11.0.1",
"@nestjs/microservices": "^11.1.1",
"@nestjs/platform-express": "^11.0.1",

Node.js version

22.13.0

In which operating systems have you tested?

Other

No response

Stormix commented 4 weeks ago

If this isn't an intended limitation, I’d be happy to submit a PR to address it.

kamilmysliwiec commented 4 weeks ago

Yes, please. Contributions are more than welcome!