Skip to content

Instantly share code, notes, and snippets.

@thiagotigaz
Last active February 26, 2022 07:25
Show Gist options
  • Save thiagotigaz/a8b2f45bccfd85bc99b9c4e6b93348bc to your computer and use it in GitHub Desktop.
Save thiagotigaz/a8b2f45bccfd85bc99b9c4e6b93348bc to your computer and use it in GitHub Desktop.
NodeJS Microservices with NestJS, Kafka, and Kubernetes - Part 3
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
} from '@nestjs/common';
import { ServicesService } from './services.service';
import { CreateServiceDto, UpdateServiceDto } from '@limascloud/common-dto';
@Controller('services')
export class ServicesController {
constructor(private readonly servicesService: ServicesService) {}
@Post()
create(@Body() createServiceDto: CreateServiceDto) {
return this.servicesService.create(createServiceDto);
}
@Get()
findAll() {
return this.servicesService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.servicesService.findOne(+id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() updateServiceDto: UpdateServiceDto) {
return this.servicesService.update(+id, updateServiceDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.servicesService.remove(+id);
}
}
import { Inject, Injectable } from '@nestjs/common';
import { CreateServiceDto, UpdateServiceDto } from '@limascloud/common-dto';
import { Producer } from '@nestjs/microservices/external/kafka.interface';
import { Logger } from '@nestjs/common';
@Injectable()
export class ServicesService {
constructor(@Inject('KAFKA_PRODUCER') private kafkaProducer: Producer) {}
create(createServiceDto: CreateServiceDto) {
const id = Math.floor(Math.random() * 100);
this.sendKafkaEvent(`${id}`, {
eventType: 'ServiceCreated',
id,
...createServiceDto,
});
return 'This action adds a new service';
}
findAll() {
return `This action returns all services`;
}
findOne(id: number) {
return `This action returns a #${id} service`;
}
update(id: number, updateServiceDto: UpdateServiceDto) {
updateServiceDto.id = id;
this.sendKafkaEvent(`${id}`, {
eventType: 'ServiceUpdated',
...updateServiceDto,
});
return `This action updates a #${id} service`;
}
remove(id: number) {
this.sendKafkaEvent(`${id}`, { eventType: 'ServiceDeleted', id });
return `This action removes a #${id} service`;
}
sendKafkaEvent(key, value) {
const message = { key, value: JSON.stringify(value) };
Logger.debug(
`sending message: ${JSON.stringify(message, null, 2)}`,
'ServicesService',
);
this.kafkaProducer.send({
topic: 'services',
messages: [{ key, value: JSON.stringify(value) }],
});
}
}
#!/bin/bash
cd api
# creates a blank microservices project under apps/microservices and converts the api project in a monorepo. Also moves current api code to apps/api
nest g app microservices
# Delete all generated microservices code and copy original content from the original project
rm -rf apps/microservices/src
cp -r ../microservices/src apps/microservices
# Move to the root of the repository. It's time to delete the old microservices project and move all files under api to the root of the repository
cd ..
rm -rf microservices api/README.md
mv api/.* .
mv api/* .
# Remove empty api folder and install necessary dependencies for the microservices project (these where listed in the original microservices/package.json)
rm -rf api
npm i @nestjs/event-emitter class-transformer
# OPTIONAL, open package.json, modify name property to microservices-nestjs-k8 instead of api
export * from './event.dto';
export * from './create-service.dto';
export * from './delete-service.dto';
export * from './kafka-service.dto';
export * from './update-service.dto';
export * from './common-dto.module';
export * from './common-dto.service';
export * from './services/dto';
import { Controller, Logger, ValidationPipe } from '@nestjs/common';
import { EventPattern, Payload } from '@nestjs/microservices';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';
import {
KafkaServiceDto,
CreateServiceDto,
UpdateServiceDto,
DeleteServiceDto,
} from '@limascloud/common-dto';
@Controller()
export class ServicesController {
constructor(private eventEmitter: EventEmitter2) {}
@EventPattern('services')
serviceEvent(@Payload(new ValidationPipe()) { value }: KafkaServiceDto) {
Logger.debug(value, 'ServicesController - serviceEvent');
this.eventEmitter.emit(value.eventType, value);
}
@OnEvent('ServiceCreated')
handleServiceCreatedEvent(createServiceDto: CreateServiceDto) {
Logger.debug(
createServiceDto,
'ServicesController - handleServiceCreatedEvent',
);
}
@OnEvent('ServiceUpdated')
handleServiceUpdatedEvent(updateServiceDto: UpdateServiceDto) {
Logger.debug(
updateServiceDto,
'ServicesController - handleServiceUpdatedEvent',
);
}
@OnEvent('ServiceDeleted')
handleServiceDeletedEvent(deleteServiceDto: DeleteServiceDto) {
Logger.debug(
deleteServiceDto,
'ServicesController - handleServiceDeletedEvent',
);
}
}
#!/bin/bash
# Moves dtos from microservices project to new created library, and deletes the dtos from the api projects.
# File relative references to dtos needs to be modified to new lib location.
# From the repository root directory
mkdir -p libs/common-dto/src/services/dto
touch libs/common-dto/src/services/dto/index.ts
mv apps/microservices/src/services/dto/* libs/common-dto/src/services/dto
rm -rf apps/microservices/src/services/dto apps/api/src/services/dto
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment