Try to create "Hybrid app" REST + NATS from official docs: https://docs.nestjs.com/faq/hybrid-application
but
- if add cred options like
authentiacator: credsAuthenticator(new TextEncoder().encode(creds)),
in two place, both in main.ts:
async function bootstrap() {
const app = await NestFactory.create(AppModule, {cors: true});
const microService = await app.connectMicroservice({
transport: Transport.NATS,
options: {/* ... */}
})
await microService.listen();
await app.listen();
//...
- and in app.module.ts:
@Module({
imports: [
ClientsModule.register([{
transport: Transport.NATS,
options: //...
The docker detail logs twice authenticate calls
- if cred placed only single place
- app throwing "NatsError: 'Authorization Violation'"
- if in app.module not add
ClientsModule.registerat all
- not working DI
- if in main.ts not add
connectMicroservice({...}).listen()at all
- it runs without error, and in controller works
.client.emit(pattern, data)(and NATS log one Authentication message) but @MessagePattern receiving not working at all. (The oposite side logs that no responders)
So... how to deduplicate options creds (and most important: deduplicate twice authenticating)
Or it exact really that was right?
Upd: Part of solution to deduplicate code is by adding ClientsModule.registerAsync to app.module.ts and Configurer.getNatsConfig to main.ts:
// configure.root.ts
export class Configurer {
static getNatsConfig(configService?: ConfigService){
let servers = configService?.get<string>('NATS') ?? process.env.S_AVE_NATS;
// process.env fallback to early direct call Configurer.getNatsConfig(undefined)
return {
transport: Transport.NATS,
options: {
servers: servers.split(' '),
authenticator: credsAuthenticator(new TextEncoder().encode(stringOfNatsUserCredsFile)),
name: 'service-subscriber',
}
}
}, // ...
}
// async launcher
export const natsConfigAsync: any = [{
name: 'NATS',
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) =>
(Configurer.getNatsConfig(configService))
}]
// main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule, { cors: true });
await app.connectMicroservice({
name: 'S_AVE',
... Configurer.getNatsConfig(),
});
await app.startAllMicroservices();
let server = await app.listen(process.env.PORT || 3000);
console.log(`serve on port: ${process.env.PORT || 3000}`);
}
bootstrap();
// app.module.ts
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true, envFilePath: `.env.${process.env.NODE_ENV || 'development'}`}),
TypeOrmModule.forRootAsync(typeOrmConfigAsync),
TypeOrmModule.forFeature([UserEntity]),
ClientsModule.registerAsync(natsConfigAsync), // TODO: Fix duplicate connection
AuthModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
- but it still twice create connection (by the NATS log)