#Microservices and RestFul APIs

21 messages · Page 1 of 1 (latest)

dim breach
#

Just wanted to ask. Is it possible for a Nest Microservice to also expose a Rest API?

Like, what I am thinking is that suppose I have an Accounts microsercice. Is it possible for it to expose an API (say, a CRUD API to create accounts and such), and also listen ti incoming messages/publish incoming messages? So, suppose a Billing service sends a message that a payment was declined. Can the Accounts service listen to that too and lock the associated account in response to the received message?

I ask because it kinda looks like from the docs that it’s an either/or thing. Either you expose a REST api or you function as a Microservice.

Thank you.

limpid igloo
#

you can definitely setup a hybrid nestjs application

dim breach
#

Really? Are there any docs for doing that?

limpid igloo
#

so I think it doesn't specifically say it on the microservices page on the docs

dim breach
#

I’m following this part of the docs.

https://docs.nestjs.com/microservices/basics

It kind of makes me think it’s either or because by using the createMicroservice() method, it doesn’t seem to create an HTTP server too like the traditional.

limpid igloo
#

it doesn't state that you can, but you can make an application listen for events/messages and take incoming http requests

dim breach
#

What do I need to change for it to do that?

limpid igloo
#
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import * as cors from 'cors';
import { Logger } from '@nestjs/common';

async function bootstrap() {
  const logger = new Logger('BOOTRSTRAP');
  const app = await NestFactory.create(AppModule);
  const config = app.get<ConfigService>(ConfigService);
  const port = config.get('PORT');

  app.connectMicroservice({
    transport: Transport.TCP,
    options: {
      host: 'localhost',
      port: //whatever port is not being listened
    }
  })
  await app.listen(port, () => logger.debug(`Server running on port ${port}`));
}

bootstrap();
#

so it would kinda look like this

#

from the perspective of you connecting it to a microservice that it would listen for events

#

and you would register it where you are going to be emitting events from

#

where I'm stating transport: Transport.TCP Transport would be imported from the @nestjs/microservices library

limpid igloo
dim breach
#

Okay. I can try that I suppose. Thanks.

Wish the docs would include it. Lol.

limpid igloo
#

It's a pretty fast pace video, but it essentially tells you how to implement a hybrid application, standalone microservices taht just listen for events and how to emit them from an application

#

I found it

#

@dim breach

dim breach
#

Oh. Okay.. that works. Thank you 🙂