This app responds to HTTP GET requests with a greeting. It also listens as a TCP microservice for messages with command 'sum' and returns the sum of numbers.
import { Controller, Get } from '@nestjs/common';
import { MessagePattern, Payload } from '@nestjs/microservices';
import { NestFactory } from '@nestjs/core';
import { Module } from '@nestjs/common';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
@Controller()
class AppController {
@Get()
getHello(): string {
return 'Hello from HTTP!';
}
@MessagePattern({ cmd: 'sum' })
sum(@Payload() data: number[]): number {
return (data || []).reduce((a, b) => a + b, 0);
}
}
@Module({
controllers: [AppController],
})
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.connectMicroservice<MicroserviceOptions>({
transport: Transport.TCP,
options: { port: 8877 },
});
await app.startAllMicroservices();
await app.listen(3000);
}
bootstrap();