Skip to content

Commit

Permalink
inclusão dos apps em monorepo do nestjs: payments e orders. Integraçã…
Browse files Browse the repository at this point in the history
…o dos pedidos com Kafka.
  • Loading branch information
JonatasMSantos committed Oct 2, 2023
1 parent e81482f commit db9f7e2
Show file tree
Hide file tree
Showing 32 changed files with 502 additions and 78 deletions.
4 changes: 3 additions & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@
"customizations": {
"vscode": {
"extensions": [
"ms-azuretools.vscode-docker",
"humao.rest-client",
"esbenp.prettier-vscode"
"esbenp.prettier-vscode",
"prisma.prisma"
]
}
},
Expand Down
2 changes: 2 additions & 0 deletions .docker/mysql/init.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
CREATE DATABASE IF NOT EXISTS `orders` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci
CREATE DATABASE IF NOT EXISTS `payments` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,6 @@ lerna-debug.log*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/extensions.json

.history/
74 changes: 8 additions & 66 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,73 +1,15 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
</p>
## Microserviço com Nestjs + Kafka

[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
### Fluxo

<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
1. Orders publica mensagem no Kafka

## Description
2. Payments consome mensagem do Kafka (pagamento realizado)

[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
3. Payments processou o pagamento

## Installation
4. Payments publicou mensagem no Kafka

```bash
$ npm install
```
5. Orders consome mensagem no Kafka (pagamento realizado)

## Running the app

```bash
# development
$ npm run start

# watch mode
$ npm run start:dev

# production mode
$ npm run start:prod
```

## Test

```bash
# unit tests
$ npm run test

# e2e tests
$ npm run test:e2e

# test coverage
$ npm run test:cov
```

## Support

Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).

## Stay in touch

- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)

## License

Nest is [MIT licensed](LICENSE).
6. Orders altera o status do pedido
14 changes: 13 additions & 1 deletion api.http
Original file line number Diff line number Diff line change
@@ -1 +1,13 @@
GET http://localhost:3000/
GET http://localhost:3000/orders

###
POST http://localhost:3000/orders
Content-Type: application/json

{
"client_id": 1,
"price": 100
}

###
GET http://localhost:3001/payments
3 changes: 3 additions & 0 deletions apps/orders/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
# Keep environment variables out of version control
.env
10 changes: 10 additions & 0 deletions apps/orders/prisma/migrations/20231002114824_init/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
-- CreateTable
CREATE TABLE `Order` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`price` INTEGER NOT NULL,
`client_id` INTEGER NOT NULL,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`status` ENUM('PENDING', 'PAYED', 'CANCELLED') NOT NULL,

PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
3 changes: 3 additions & 0 deletions apps/orders/prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "mysql"
26 changes: 26 additions & 0 deletions apps/orders/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
provider = "prisma-client-js"
output = "../../../node_modules/.prisma/client/orders"
}

datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}

model Order {
id Int @id @default(autoincrement())
price Int
client_id Int
created_at DateTime @default(now())
status OrderStatus
}

enum OrderStatus {
PENDING
PAYED
CANCELLED
}
14 changes: 14 additions & 0 deletions apps/orders/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
import { NestFactory } from '@nestjs/core';
import { OrdersModule } from './orders.module';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';

async function bootstrap() {
const app = await NestFactory.create(OrdersModule);
app.connectMicroservice<MicroserviceOptions>({
transport: Transport.KAFKA,
options: {
client: {
brokers: ['kafka:29092']
},
consumer: {
groupId: 'orders-consumer',
}
}
})

await app.startAllMicroservices()
await app.listen(3000);
}
bootstrap();
25 changes: 21 additions & 4 deletions apps/orders/src/orders.controller.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,29 @@
import { Controller, Get } from '@nestjs/common';
import { Body, Controller, Get, Post } from '@nestjs/common';
import { OrdersService } from './orders.service';
import { Prisma, OrderStatus } from '.prisma/client/orders';
import { MessagePattern, Payload } from '@nestjs/microservices';

@Controller()
@Controller('orders')
export class OrdersController {
constructor(private readonly ordersService: OrdersService) {}

@Get()
getHello(): string {
return this.ordersService.getHello();
getHello(): Promise<any> {
return this.ordersService.all();
}

@Post()
create(@Body() data: Prisma.OrderCreateInput): Promise<any> {
return this.ordersService.create(data);
}

@MessagePattern('payments')
async complete(@Payload() message: any) {
await this.ordersService.complete(
message.order_id,
message.status === 'APPROVED'
? OrderStatus.PAYED
: OrderStatus.CANCELLED,
);
}
}
15 changes: 14 additions & 1 deletion apps/orders/src/orders.module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
import { Module } from '@nestjs/common';
import { OrdersController } from './orders.controller';
import { OrdersService } from './orders.service';
import { PrismaModule } from './prisma/prisma.module';
import { ClientsModule, Transport } from '@nestjs/microservices';

@Module({
imports: [],
imports: [PrismaModule, ClientsModule.register([
{
name: 'ORDERS_SERVICE',
transport: Transport.KAFKA,
options: {
client: {
clientId: 'orders',
brokers: ['kafka:29092']
}
}
}
])],
controllers: [OrdersController],
providers: [OrdersService],
})
Expand Down
36 changes: 33 additions & 3 deletions apps/orders/src/orders.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,38 @@
import { Injectable } from '@nestjs/common';
import { Inject, Injectable } from '@nestjs/common';
import { PrismaService } from './prisma/prisma/prisma.service';
import { Prisma, OrderStatus } from '.prisma/client/orders';
import { ClientKafka } from '@nestjs/microservices';
import { lastValueFrom } from 'rxjs';

@Injectable()
export class OrdersService {
getHello(): string {
return 'Hello World!';
constructor(
private prismaService: PrismaService,
@Inject('ORDERS_SERVICE') private kafkaClient: ClientKafka,
) {}

all(): Promise<any> {
return this.prismaService.order.findMany();
}

async create(data: Prisma.OrderCreateInput): Promise<any> {
const order = await this.prismaService.order.create({
data: {
...data,
status: OrderStatus.PENDING,
},
});

console.log(order);

await lastValueFrom(this.kafkaClient.emit('orders', order));
return order;
}

complete(id: number, status: OrderStatus) {
return this.prismaService.order.update({
where: { id },
data: { status },
});
}
}
9 changes: 9 additions & 0 deletions apps/orders/src/prisma/prisma.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Global, Module } from '@nestjs/common';
import { PrismaService } from './prisma/prisma.service';

@Global()
@Module({
providers: [PrismaService],
exports: [PrismaService]
})
export class PrismaModule {}
17 changes: 17 additions & 0 deletions apps/orders/src/prisma/prisma/prisma.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '.prisma/client/orders';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {

async onModuleInit() {
await this.$connect();
}

async enableShutdownHooks(app: any) {
process.on("beforeExit", async () => {
await app.close();
})
}

}
3 changes: 3 additions & 0 deletions apps/payments/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
# Keep environment variables out of version control
.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
-- CreateTable
CREATE TABLE `Payment` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`amount` DOUBLE NOT NULL,
`order_id` INTEGER NOT NULL,
`client_id` INTEGER NOT NULL,
`create_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`status` ENUM('APPROVED', 'REJECT') NOT NULL,

PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
3 changes: 3 additions & 0 deletions apps/payments/prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "mysql"
26 changes: 26 additions & 0 deletions apps/payments/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
provider = "prisma-client-js"
output = "../../../node_modules/.prisma/client/payments"
}

datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}

model Payment {
id Int @id @default(autoincrement())
amount Float
order_id Int
client_id Int
create_at DateTime @default(now())
status PaymentStatus
}

enum PaymentStatus {
APPROVED
REJECT
}
22 changes: 22 additions & 0 deletions apps/payments/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { NestFactory } from '@nestjs/core';
import { PaymentsModule } from './payments.module';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';

async function bootstrap() {
const app = await NestFactory.create(PaymentsModule);
app.connectMicroservice<MicroserviceOptions>({
transport: Transport.KAFKA,
options: {
client: {
brokers: ['kafka:29092']
},
consumer: {
groupId: 'payments-consumer',
}
}
})

await app.startAllMicroservices()
await app.listen(3001);
}
bootstrap();
Loading

0 comments on commit db9f7e2

Please sign in to comment.