Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow for microservice options to come from the di container #12622

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

jmcdo29
Copy link
Member

@jmcdo29 jmcdo29 commented Oct 20, 2023

Microservices are now able to be created by getting their options from within the DI container itself. This has been a long requested feature of developers and I finally had some time to work through how we could possibly let this happen.

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Other... Please describe:

What is the current behavior?

There is no way to apply the microservice config for a microservice server, by getting the configuration from within the DI container, like from the ConfigService

Issue Number:

What is the new behavior?

Microservices are now able to be configured via a provider that was registered within the DI tree, without creating a new NestFactory.createApplicationContext() first. Devs are now able to pass a useFactory and inject as a part of the options object passed to NestFactory.createMicroservice() which will allow for Nest to find the tokens in the inject and pass them to the useFactory to get the configuration for the microservice. E.g.:

const port = 4444;

@Injectable()
class RpcOptionsProvider {
  getOptions(): TcpClientOptions {
    return {
      transport: Transport.TCP,
      options: {
        port,
        host: '0.0.0.0',
      },
    };
  }
}

@Controller()
class RpcController {
  @MessagePattern({ cmd: 'sum' })
  sumPayload(@Payload() payload: number[]) {
    return payload.reduce((a, b) => a + b, 0);
  }
}

@Module({
  imports: [
    ClientsModule.register([
      {
        name: 'RPC_CLIENT',
        transport: Transport.TCP,
        options: {
          port,
          host: '0.0.0.0',
        },
      },
    ]),
  ],
  controllers: [RpcController],
  providers: [RpcOptionsProvider],
})
class RpcModule {}

const bootstrap = async () => {
  await NestFactory.createMicroservice<
    AsyncOptions<MicroserviceOptions>
  >(RpcModule, {
    logger: false,
    inject: [RpcOptionsProvider],
    useFactory: (optionsProvider: RpcOptionsProvider) =>
      optionsProvider.getOptions(),
  });
  await app.listen();
}
bootstrap();

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

@coveralls
Copy link

coveralls commented Oct 20, 2023

Pull Request Test Coverage Report for Build fcc8bd07-d1f6-4348-a848-ddd8d3ad7704

  • 0 of 0 changed or added relevant lines in 0 files are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage remained the same at 92.639%

Totals Coverage Status
Change from base Build 79434c05-5367-4a7a-a04c-0f91cc807577: 0.0%
Covered Lines: 6469
Relevant Lines: 6983

💛 - Coveralls

@jmcdo29 jmcdo29 force-pushed the feat/async-microservce-config branch from 7218e44 to 7ed071d Compare October 20, 2023 21:42
Microservices are now able to be created by getting their options
from within the DI container itself. This has been a long requested
feature of developers and I finally had some time to work through how
we could possibly let this happen.
@jmcdo29 jmcdo29 force-pushed the feat/async-microservce-config branch from 7ed071d to 2f22522 Compare October 21, 2023 00:08
Comment on lines +70 to +77
app = await NestFactory.createMicroservice<
AsyncOptions<MicroserviceOptions>
>(RpcModule, {
logger: false,
inject: [RpcOptionsProvider],
useFactory: (optionsProvider: RpcOptionsProvider) =>
optionsProvider.getOptions(),
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we couldn't have something to make this feels like a traditional dynamic module import...

something like:

const app = await NestFactory.createMicroservice(
  RpcModule,
  MicroserviceOptionsFactory.createAsync<MicroserviceOptions>({
    inject: [RpcOptionsProvider],
    useFactory: (optionsProvider: RpcOptionsProvider) => ({
      logger: false,
      ...optionsProvider.getOptions(),
    })
  })
)

perharps that's too overkill (or impossible) to have? yeah...

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could, just to give a unified API, but the underlying code and how it gets read in the server options resolver would pretty much be the same. This would just be a simple wrapper around the object we already return, and I don't think there would be much benefit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Overthink dependency injection, performance and more (feedback)
4 participants