nest
nest copied to clipboard
feat: allow for microservice options to come from the di container
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:
- [X] The commit message follows our guidelines: https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md
- [X] Tests for the changes have been added (for bug fixes / features)
- [ ] Docs have been added / updated (for bug fixes / features)
PR Type
What kind of change does this PR introduce?
- [ ] Bugfix
- [X] 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:
- #12620
- #2343
- #4410
- #5102
- #7108
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
- [X] No
Other information
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 | |
|---|---|
| Change from base Build 79434c05-5367-4a7a-a04c-0f91cc807577: | 0.0% |
| Covered Lines: | 6469 |
| Relevant Lines: | 6983 |