Reputation: 79
Can a NestJS backend be a microservice and an API Rest as the same time ?
main.ts for a microservice:
const microservice = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule,
{
transport: Transport.KAFKA,
// ...options, client, consumer, etc...
},
);
await microservice.listen();
main.ts for a REST API:
const app = await NestFactory.create(AppModule)
await app.listen(3000);
How to mix use create and createMicroservice in the same main.ts ? Should I use a Gateway API with the serviceA as microservice and serviceB as REST API ?
Upvotes: 2
Views: 2415
Reputation: 70131
Pretty sure what you're looking for is a hybrid application. You create the regular HTTP application with NestFactory.create()
and then you use app.connectMicroservice()
to add microservices that should run alongside the HTTP server.
Example from the docs:
const app = await NestFactory.create(AppModule);
// microservice #1
const microserviceTcp = app.connectMicroservice<MicroserviceOptions>({
transport: Transport.TCP,
options: {
port: 3001,
},
});
// microservice #2
const microserviceRedis = app.connectMicroservice<MicroserviceOptions>({
transport: Transport.REDIS,
options: {
host: 'localhost',
port: 6379,
},
});
await app.startAllMicroservices();
await app.listen(3001);
Upvotes: 4