Nâng CaoNestJS iconNestJS

Hybrid application trong NestJS — serve HTTP và Microservice transport cùng lúc?

Hybrid app cho phép một NestJS app expose cả HTTP REST endpoints lẫn microservice message handlers — hữu ích khi muốn API Gateway cũng lắng nghe events.

typescript
// main.ts
const app = await NestFactory.create(AppModule);

// Attach microservice
app.connectMicroservice<MicroserviceOptions>({
  transport: Transport.TCP,
  options: { host: '0.0.0.0', port: 3001 },
});

// Start cả hai
await app.startAllMicroservices(); // Phải gọi trước listen
await app.listen(3000);

Controller vừa có @Get() cho HTTP vừa có @MessagePattern() cho RPC:

typescript
@Controller('orders')
export class OrdersController {
  @Get()
  async findAll() { ... }  // HTTP

  @MessagePattern({ cmd: 'get_orders' })
  async findAllRpc(@Payload() data: any) { ... }  // TCP/RPC
}

Use case: API Gateway nhận HTTP từ frontend, đồng thời lắng nghe events từ internal services qua Kafka/TCP để cập nhật cache.

Xem toàn bộ NestJS cùng filter theo level & chủ đề con.

Mở danh sách NestJS