├── .gitignore ├── README.md ├── docker-compose.yml ├── http-api-gateway ├── .dockerignore ├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── Dockerfile ├── README.md ├── nest-cli.json ├── package-lock.json ├── package.json ├── src │ ├── app.module.ts │ ├── main.ts │ ├── nats-client │ │ └── nats-client.module.ts │ ├── payments │ │ ├── dto │ │ │ └── CreatePayment.dto.ts │ │ ├── payments.controller.ts │ │ └── payments.module.ts │ └── users │ │ ├── dtos │ │ └── CreateUser.dto.ts │ │ ├── users.controller.ts │ │ └── users.module.ts ├── test │ ├── app.e2e-spec.ts │ └── jest-e2e.json ├── tsconfig.build.json └── tsconfig.json ├── payments-microservice ├── .dockerignore ├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── Dockerfile ├── README.md ├── nest-cli.json ├── package-lock.json ├── package.json ├── src │ ├── app.module.ts │ ├── main.ts │ ├── nats-client │ │ └── nats-client.module.ts │ ├── payments │ │ ├── dtos │ │ │ └── CreatePayment.dto.ts │ │ ├── payments.controller.ts │ │ ├── payments.module.ts │ │ └── payments.service.ts │ └── typeorm │ │ └── entities │ │ ├── Payment.ts │ │ └── User.ts ├── test │ ├── app.e2e-spec.ts │ └── jest-e2e.json ├── tsconfig.build.json └── tsconfig.json └── users-microservice ├── .dockerignore ├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── Dockerfile ├── README.md ├── nest-cli.json ├── package-lock.json ├── package.json ├── src ├── app.module.ts ├── main.ts ├── typeorm │ └── entities │ │ ├── Payment.ts │ │ └── User.ts └── users │ ├── dtos │ └── CreateUser.dto.ts │ ├── users.controller.ts │ ├── users.module.ts │ └── users.service.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Nest.js Microservices with NATS, MySQL, & Docker 2 | 3 | This repository contains 3 Nest.js projects: 4 | 5 | - http-api-gateway 6 | - payments-microservice 7 | - users-microservice 8 | 9 | You can find the video tutorial for this project [here]('https://youtube.com/) 10 | 11 | # Getting Started 12 | 13 | Want to set this up locally on your own? The best way to set this project up is by using Docker. 14 | 15 | 1. Pull down this repository and make sure you install each projects' dependencies by running `npm run install`. 16 | 17 | 2. Ensure Docker is running then run `docker-compose up --build` to build the container, images, and pull down the mysql and nats image from Docker. 18 | 19 | 3. Verify that all services are up and running. The HTTP Server runs on port 3000. 20 | 21 | # Application Structure 22 | 23 | ### HTTP API Gateway 24 | 25 | This is a [hybrid application](https://docs.nestjs.com/faq/hybrid-application) that uses both HTTP and NATS as sources to listen to requests from. This is the entry point to the entire platform. It forwards the request by publishing a message to the NATS server, and then the NATS server distributes it to its subscribers. 26 | 27 | Any HTTP API endpoints should be defined in this project. 28 | 29 | ### Payments Microservice 30 | 31 | This is a sample microservice that has a createPayment event handler from the NATS server whenever it is triggered. It will create a payment record and save it to the database. 32 | 33 | ### Users Microservice 34 | 35 | This is a user microservice that has a createUser event handler from the NATS server whenever it is triggered. It will create a user record and save it to the database. 36 | 37 | 38 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | api_gateway: 3 | build: ./http-api-gateway 4 | ports: 5 | - "3000:3000" 6 | volumes: 7 | - ./http-api-gateway/src:/usr/src/app/src 8 | command: npm run start:dev 9 | environment: 10 | - PORT=3000 11 | users_microservice: 12 | build: ./users-microservice 13 | volumes: 14 | - ./users-microservice/src:/usr/src/app/src 15 | command: npm run start:dev 16 | payments_microservice: 17 | build: ./payments-microservice 18 | volumes: 19 | - ./payments-microservice/src:/usr/src/app/src 20 | command: npm run start:dev 21 | nats: 22 | image: nats 23 | ports: 24 | - 4222:4222 25 | mysql_db: 26 | image: mysql 27 | ports: 28 | - "3307:3307" 29 | environment: 30 | - MYSQL_ROOT_PASSWORD=root_password_123 31 | - MYSQL_DATABASE=nestjs_db 32 | - MYSQL_USER=testuser 33 | - MYSQL_PASSWORD=testuser123 34 | - MYSQL_TCP_PORT=3307 35 | -------------------------------------------------------------------------------- /http-api-gateway/.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /http-api-gateway/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | tsconfigRootDir: __dirname, 6 | sourceType: 'module', 7 | }, 8 | plugins: ['@typescript-eslint/eslint-plugin'], 9 | extends: [ 10 | 'plugin:@typescript-eslint/recommended', 11 | 'plugin:prettier/recommended', 12 | ], 13 | root: true, 14 | env: { 15 | node: true, 16 | jest: true, 17 | }, 18 | ignorePatterns: ['.eslintrc.js'], 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': 'off', 22 | '@typescript-eslint/explicit-module-boundary-types': 'off', 23 | '@typescript-eslint/no-explicit-any': 'off', 24 | }, 25 | }; 26 | -------------------------------------------------------------------------------- /http-api-gateway/.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | pnpm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # OS 15 | .DS_Store 16 | 17 | # Tests 18 | /coverage 19 | /.nyc_output 20 | 21 | # IDEs and editors 22 | /.idea 23 | .project 24 | .classpath 25 | .c9/ 26 | *.launch 27 | .settings/ 28 | *.sublime-workspace 29 | 30 | # IDE - VSCode 31 | .vscode/* 32 | !.vscode/settings.json 33 | !.vscode/tasks.json 34 | !.vscode/launch.json 35 | !.vscode/extensions.json -------------------------------------------------------------------------------- /http-api-gateway/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /http-api-gateway/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:18 2 | 3 | WORKDIR /usr/src/app 4 | 5 | COPY package.json ./ 6 | COPY package-lock.json ./ 7 | 8 | RUN npm install 9 | 10 | COPY . . 11 | -------------------------------------------------------------------------------- /http-api-gateway/README.md: -------------------------------------------------------------------------------- 1 |

2 | Nest Logo 3 |

4 | 5 | [circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456 6 | [circleci-url]: https://circleci.com/gh/nestjs/nest 7 | 8 |

A progressive Node.js framework for building efficient and scalable server-side applications.

9 |

10 | NPM Version 11 | Package License 12 | NPM Downloads 13 | CircleCI 14 | Coverage 15 | Discord 16 | Backers on Open Collective 17 | Sponsors on Open Collective 18 | 19 | Support us 20 | 21 |

22 | 24 | 25 | ## Description 26 | 27 | [Nest](https://github.com/nestjs/nest) framework TypeScript starter repository. 28 | 29 | ## Installation 30 | 31 | ```bash 32 | $ npm install 33 | ``` 34 | 35 | ## Running the app 36 | 37 | ```bash 38 | # development 39 | $ npm run start 40 | 41 | # watch mode 42 | $ npm run start:dev 43 | 44 | # production mode 45 | $ npm run start:prod 46 | ``` 47 | 48 | ## Test 49 | 50 | ```bash 51 | # unit tests 52 | $ npm run test 53 | 54 | # e2e tests 55 | $ npm run test:e2e 56 | 57 | # test coverage 58 | $ npm run test:cov 59 | ``` 60 | 61 | ## Support 62 | 63 | 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). 64 | 65 | ## Stay in touch 66 | 67 | - Author - [Kamil Myśliwiec](https://kamilmysliwiec.com) 68 | - Website - [https://nestjs.com](https://nestjs.com/) 69 | - Twitter - [@nestframework](https://twitter.com/nestframework) 70 | 71 | ## License 72 | 73 | Nest is [MIT licensed](LICENSE). 74 | -------------------------------------------------------------------------------- /http-api-gateway/nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/nest-cli", 3 | "collection": "@nestjs/schematics", 4 | "sourceRoot": "src", 5 | "compilerOptions": { 6 | "deleteOutDir": true 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /http-api-gateway/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "http-api-gateway", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "build": "nest build", 10 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 11 | "start": "nest start", 12 | "start:dev": "nest start --watch", 13 | "start:debug": "nest start --debug --watch", 14 | "start:prod": "node dist/main", 15 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 16 | "test": "jest", 17 | "test:watch": "jest --watch", 18 | "test:cov": "jest --coverage", 19 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 20 | "test:e2e": "jest --config ./test/jest-e2e.json" 21 | }, 22 | "dependencies": { 23 | "@nestjs/common": "^10.0.0", 24 | "@nestjs/core": "^10.0.0", 25 | "@nestjs/microservices": "^10.2.10", 26 | "@nestjs/platform-express": "^10.0.0", 27 | "class-transformer": "^0.5.1", 28 | "class-validator": "^0.14.0", 29 | "nats": "^2.18.0", 30 | "reflect-metadata": "^0.1.13", 31 | "rxjs": "^7.8.1" 32 | }, 33 | "devDependencies": { 34 | "@nestjs/cli": "^10.0.0", 35 | "@nestjs/schematics": "^10.0.0", 36 | "@nestjs/testing": "^10.0.0", 37 | "@types/express": "^4.17.17", 38 | "@types/jest": "^29.5.2", 39 | "@types/node": "^20.3.1", 40 | "@types/supertest": "^2.0.12", 41 | "@typescript-eslint/eslint-plugin": "^6.0.0", 42 | "@typescript-eslint/parser": "^6.0.0", 43 | "eslint": "^8.42.0", 44 | "eslint-config-prettier": "^9.0.0", 45 | "eslint-plugin-prettier": "^5.0.0", 46 | "jest": "^29.5.0", 47 | "prettier": "^3.0.0", 48 | "source-map-support": "^0.5.21", 49 | "supertest": "^6.3.3", 50 | "ts-jest": "^29.1.0", 51 | "ts-loader": "^9.4.3", 52 | "ts-node": "^10.9.1", 53 | "tsconfig-paths": "^4.2.0", 54 | "typescript": "^5.1.3" 55 | }, 56 | "jest": { 57 | "moduleFileExtensions": [ 58 | "js", 59 | "json", 60 | "ts" 61 | ], 62 | "rootDir": "src", 63 | "testRegex": ".*\\.spec\\.ts$", 64 | "transform": { 65 | "^.+\\.(t|j)s$": "ts-jest" 66 | }, 67 | "collectCoverageFrom": [ 68 | "**/*.(t|j)s" 69 | ], 70 | "coverageDirectory": "../coverage", 71 | "testEnvironment": "node" 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /http-api-gateway/src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { UsersModule } from './users/users.module'; 3 | import { PaymentsModule } from './payments/payments.module'; 4 | 5 | @Module({ 6 | imports: [UsersModule, PaymentsModule], 7 | controllers: [], 8 | providers: [], 9 | }) 10 | export class AppModule {} 11 | -------------------------------------------------------------------------------- /http-api-gateway/src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | import { ValidationPipe } from '@nestjs/common'; 4 | 5 | async function bootstrap() { 6 | const app = await NestFactory.create(AppModule); 7 | app.useGlobalPipes(new ValidationPipe()); 8 | const PORT = process.env.PORT || 3000; 9 | await app.listen(PORT, () => console.log(`Running on PORT ${PORT}`)); 10 | } 11 | 12 | bootstrap(); 13 | -------------------------------------------------------------------------------- /http-api-gateway/src/nats-client/nats-client.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { ClientsModule, Transport } from '@nestjs/microservices'; 3 | 4 | @Module({ 5 | imports: [ 6 | ClientsModule.register([ 7 | { 8 | name: 'NATS_SERVICE', 9 | transport: Transport.NATS, 10 | options: { 11 | servers: ['nats://nats'], 12 | }, 13 | }, 14 | ]), 15 | ], 16 | exports: [ 17 | ClientsModule.register([ 18 | { 19 | name: 'NATS_SERVICE', 20 | transport: Transport.NATS, 21 | options: { 22 | servers: ['nats://nats'], 23 | }, 24 | }, 25 | ]), 26 | ], 27 | }) 28 | export class NatsClientModule {} 29 | -------------------------------------------------------------------------------- /http-api-gateway/src/payments/dto/CreatePayment.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsNotEmpty, IsNumber } from 'class-validator'; 2 | 3 | export class CreatePaymentDto { 4 | @IsNumber() 5 | @IsNotEmpty() 6 | amount: number; 7 | 8 | @IsNotEmpty() 9 | userId: string; 10 | } 11 | -------------------------------------------------------------------------------- /http-api-gateway/src/payments/payments.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Inject, Post, Body } from '@nestjs/common'; 2 | import { ClientProxy } from '@nestjs/microservices'; 3 | import { CreatePaymentDto } from './dto/CreatePayment.dto'; 4 | 5 | @Controller('payments') 6 | export class PaymentsController { 7 | constructor(@Inject('NATS_SERVICE') private natsClient: ClientProxy) {} 8 | 9 | @Post() 10 | createPayment(@Body() createPaymentDto: CreatePaymentDto) { 11 | this.natsClient.emit('createPayment', createPaymentDto); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /http-api-gateway/src/payments/payments.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { NatsClientModule } from 'src/nats-client/nats-client.module'; 3 | import { PaymentsController } from './payments.controller'; 4 | 5 | @Module({ 6 | imports: [NatsClientModule], 7 | controllers: [PaymentsController], 8 | providers: [], 9 | }) 10 | export class PaymentsModule {} 11 | -------------------------------------------------------------------------------- /http-api-gateway/src/users/dtos/CreateUser.dto.ts: -------------------------------------------------------------------------------- 1 | import { 2 | IsNotEmpty, 3 | IsString, 4 | MaxLength, 5 | IsOptional, 6 | IsEmail, 7 | } from 'class-validator'; 8 | 9 | export class CreateUserDto { 10 | @IsNotEmpty() 11 | @IsString() 12 | @MaxLength(32) 13 | username: string; 14 | 15 | @IsOptional() 16 | @IsString() 17 | @MaxLength(64) 18 | displayName?: string; 19 | 20 | @IsNotEmpty() 21 | @IsEmail() 22 | email: string; 23 | } 24 | -------------------------------------------------------------------------------- /http-api-gateway/src/users/users.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Controller, 3 | Inject, 4 | Post, 5 | Body, 6 | Get, 7 | Param, 8 | HttpException, 9 | } from '@nestjs/common'; 10 | import { ClientProxy } from '@nestjs/microservices'; 11 | import { CreateUserDto } from './dtos/CreateUser.dto'; 12 | import { lastValueFrom } from 'rxjs'; 13 | 14 | @Controller('users') 15 | export class UsersController { 16 | constructor(@Inject('NATS_SERVICE') private natsClient: ClientProxy) {} 17 | 18 | @Post() 19 | createUser(@Body() createUserDto: CreateUserDto) { 20 | console.log(createUserDto); 21 | return this.natsClient.send({ cmd: 'createUser' }, createUserDto); 22 | } 23 | 24 | @Get(':id') 25 | async getUserById(@Param('id') id: string) { 26 | const user = await lastValueFrom( 27 | this.natsClient.send({ cmd: 'getUserById' }, { userId: id }), 28 | ); 29 | if (user) return user; 30 | else throw new HttpException('User Not Found', 404); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /http-api-gateway/src/users/users.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { UsersController } from './users.controller'; 3 | import { NatsClientModule } from 'src/nats-client/nats-client.module'; 4 | 5 | @Module({ 6 | imports: [NatsClientModule], 7 | controllers: [UsersController], 8 | providers: [], 9 | }) 10 | export class UsersModule {} 11 | -------------------------------------------------------------------------------- /http-api-gateway/test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { INestApplication } from '@nestjs/common'; 3 | import * as request from 'supertest'; 4 | import { AppModule } from './../src/app.module'; 5 | 6 | describe('AppController (e2e)', () => { 7 | let app: INestApplication; 8 | 9 | beforeEach(async () => { 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ 11 | imports: [AppModule], 12 | }).compile(); 13 | 14 | app = moduleFixture.createNestApplication(); 15 | await app.init(); 16 | }); 17 | 18 | it('/ (GET)', () => { 19 | return request(app.getHttpServer()) 20 | .get('/') 21 | .expect(200) 22 | .expect('Hello World!'); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /http-api-gateway/test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /http-api-gateway/tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /http-api-gateway/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "target": "ES2021", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./", 13 | "incremental": true, 14 | "skipLibCheck": true, 15 | "strictNullChecks": false, 16 | "noImplicitAny": false, 17 | "strictBindCallApply": false, 18 | "forceConsistentCasingInFileNames": false, 19 | "noFallthroughCasesInSwitch": false 20 | }, 21 | "watchOptions": { 22 | // Use a dynamic polling instead of system’s native events for file changes. 23 | "watchFile": "dynamicPriorityPolling", 24 | "watchDirectory": "dynamicPriorityPolling", 25 | "excludeDirectories": ["**/node_modules", "dist"] 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /payments-microservice/.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /payments-microservice/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | tsconfigRootDir: __dirname, 6 | sourceType: 'module', 7 | }, 8 | plugins: ['@typescript-eslint/eslint-plugin'], 9 | extends: [ 10 | 'plugin:@typescript-eslint/recommended', 11 | 'plugin:prettier/recommended', 12 | ], 13 | root: true, 14 | env: { 15 | node: true, 16 | jest: true, 17 | }, 18 | ignorePatterns: ['.eslintrc.js'], 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': 'off', 22 | '@typescript-eslint/explicit-module-boundary-types': 'off', 23 | '@typescript-eslint/no-explicit-any': 'off', 24 | }, 25 | }; 26 | -------------------------------------------------------------------------------- /payments-microservice/.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | pnpm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # OS 15 | .DS_Store 16 | 17 | # Tests 18 | /coverage 19 | /.nyc_output 20 | 21 | # IDEs and editors 22 | /.idea 23 | .project 24 | .classpath 25 | .c9/ 26 | *.launch 27 | .settings/ 28 | *.sublime-workspace 29 | 30 | # IDE - VSCode 31 | .vscode/* 32 | !.vscode/settings.json 33 | !.vscode/tasks.json 34 | !.vscode/launch.json 35 | !.vscode/extensions.json -------------------------------------------------------------------------------- /payments-microservice/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /payments-microservice/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:18 2 | 3 | WORKDIR /usr/src/app 4 | 5 | COPY package.json ./ 6 | COPY package-lock.json ./ 7 | 8 | RUN npm install 9 | 10 | COPY . . 11 | -------------------------------------------------------------------------------- /payments-microservice/README.md: -------------------------------------------------------------------------------- 1 |

2 | Nest Logo 3 |

4 | 5 | [circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456 6 | [circleci-url]: https://circleci.com/gh/nestjs/nest 7 | 8 |

A progressive Node.js framework for building efficient and scalable server-side applications.

9 |

10 | NPM Version 11 | Package License 12 | NPM Downloads 13 | CircleCI 14 | Coverage 15 | Discord 16 | Backers on Open Collective 17 | Sponsors on Open Collective 18 | 19 | Support us 20 | 21 |

22 | 24 | 25 | ## Description 26 | 27 | [Nest](https://github.com/nestjs/nest) framework TypeScript starter repository. 28 | 29 | ## Installation 30 | 31 | ```bash 32 | $ npm install 33 | ``` 34 | 35 | ## Running the app 36 | 37 | ```bash 38 | # development 39 | $ npm run start 40 | 41 | # watch mode 42 | $ npm run start:dev 43 | 44 | # production mode 45 | $ npm run start:prod 46 | ``` 47 | 48 | ## Test 49 | 50 | ```bash 51 | # unit tests 52 | $ npm run test 53 | 54 | # e2e tests 55 | $ npm run test:e2e 56 | 57 | # test coverage 58 | $ npm run test:cov 59 | ``` 60 | 61 | ## Support 62 | 63 | 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). 64 | 65 | ## Stay in touch 66 | 67 | - Author - [Kamil Myśliwiec](https://kamilmysliwiec.com) 68 | - Website - [https://nestjs.com](https://nestjs.com/) 69 | - Twitter - [@nestframework](https://twitter.com/nestframework) 70 | 71 | ## License 72 | 73 | Nest is [MIT licensed](LICENSE). 74 | -------------------------------------------------------------------------------- /payments-microservice/nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/nest-cli", 3 | "collection": "@nestjs/schematics", 4 | "sourceRoot": "src", 5 | "compilerOptions": { 6 | "deleteOutDir": true 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /payments-microservice/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "payments-microservice", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "build": "nest build", 10 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 11 | "start": "nest start", 12 | "start:dev": "nest start --watch", 13 | "start:debug": "nest start --debug --watch", 14 | "start:prod": "node dist/main", 15 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 16 | "test": "jest", 17 | "test:watch": "jest --watch", 18 | "test:cov": "jest --coverage", 19 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 20 | "test:e2e": "jest --config ./test/jest-e2e.json" 21 | }, 22 | "dependencies": { 23 | "@nestjs/common": "^10.0.0", 24 | "@nestjs/core": "^10.0.0", 25 | "@nestjs/microservices": "^10.2.10", 26 | "@nestjs/platform-express": "^10.0.0", 27 | "@nestjs/typeorm": "^10.0.1", 28 | "mysql2": "^3.6.5", 29 | "nats": "^2.18.0", 30 | "reflect-metadata": "^0.1.13", 31 | "rxjs": "^7.8.1", 32 | "typeorm": "^0.3.17" 33 | }, 34 | "devDependencies": { 35 | "@nestjs/cli": "^10.0.0", 36 | "@nestjs/schematics": "^10.0.0", 37 | "@nestjs/testing": "^10.0.0", 38 | "@types/express": "^4.17.17", 39 | "@types/jest": "^29.5.2", 40 | "@types/node": "^20.3.1", 41 | "@types/supertest": "^2.0.12", 42 | "@typescript-eslint/eslint-plugin": "^6.0.0", 43 | "@typescript-eslint/parser": "^6.0.0", 44 | "eslint": "^8.42.0", 45 | "eslint-config-prettier": "^9.0.0", 46 | "eslint-plugin-prettier": "^5.0.0", 47 | "jest": "^29.5.0", 48 | "prettier": "^3.0.0", 49 | "source-map-support": "^0.5.21", 50 | "supertest": "^6.3.3", 51 | "ts-jest": "^29.1.0", 52 | "ts-loader": "^9.4.3", 53 | "ts-node": "^10.9.1", 54 | "tsconfig-paths": "^4.2.0", 55 | "typescript": "^5.1.3" 56 | }, 57 | "jest": { 58 | "moduleFileExtensions": [ 59 | "js", 60 | "json", 61 | "ts" 62 | ], 63 | "rootDir": "src", 64 | "testRegex": ".*\\.spec\\.ts$", 65 | "transform": { 66 | "^.+\\.(t|j)s$": "ts-jest" 67 | }, 68 | "collectCoverageFrom": [ 69 | "**/*.(t|j)s" 70 | ], 71 | "coverageDirectory": "../coverage", 72 | "testEnvironment": "node" 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /payments-microservice/src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { PaymentsModule } from './payments/payments.module'; 3 | import { TypeOrmModule } from '@nestjs/typeorm'; 4 | import { Payment } from './typeorm/entities/Payment'; 5 | import { User } from './typeorm/entities/User'; 6 | 7 | @Module({ 8 | imports: [ 9 | TypeOrmModule.forRoot({ 10 | type: 'mysql', 11 | host: 'mysql_db', 12 | port: 3307, 13 | database: 'nestjs_db', 14 | entities: [Payment, User], 15 | synchronize: true, 16 | username: 'testuser', 17 | password: 'testuser123', 18 | }), 19 | PaymentsModule, 20 | ], 21 | controllers: [], 22 | providers: [], 23 | }) 24 | export class AppModule {} 25 | -------------------------------------------------------------------------------- /payments-microservice/src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | import { MicroserviceOptions, Transport } from '@nestjs/microservices'; 4 | 5 | async function bootstrap() { 6 | console.log('Payments Microservice is Running!'); 7 | const app = await NestFactory.createMicroservice( 8 | AppModule, 9 | { 10 | transport: Transport.NATS, 11 | options: { 12 | servers: ['nats://nats'], 13 | }, 14 | }, 15 | ); 16 | await app.listen(); 17 | } 18 | bootstrap(); 19 | -------------------------------------------------------------------------------- /payments-microservice/src/nats-client/nats-client.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { ClientsModule, Transport } from '@nestjs/microservices'; 3 | 4 | @Module({ 5 | imports: [ 6 | ClientsModule.register([ 7 | { 8 | name: 'NATS_SERVICE', 9 | transport: Transport.NATS, 10 | options: { 11 | servers: ['nats://nats'], 12 | }, 13 | }, 14 | ]), 15 | ], 16 | exports: [ 17 | ClientsModule.register([ 18 | { 19 | name: 'NATS_SERVICE', 20 | transport: Transport.NATS, 21 | options: { 22 | servers: ['nats://nats'], 23 | }, 24 | }, 25 | ]), 26 | ], 27 | }) 28 | export class NatsClientModule {} 29 | -------------------------------------------------------------------------------- /payments-microservice/src/payments/dtos/CreatePayment.dto.ts: -------------------------------------------------------------------------------- 1 | export class CreatePaymentDto { 2 | amount: number; 3 | userId: string; 4 | } 5 | -------------------------------------------------------------------------------- /payments-microservice/src/payments/payments.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Inject } from '@nestjs/common'; 2 | import { ClientProxy, EventPattern, Payload } from '@nestjs/microservices'; 3 | import { CreatePaymentDto } from './dtos/CreatePayment.dto'; 4 | import { PaymentsService } from './payments.service'; 5 | 6 | @Controller() 7 | export class PaymentsMicroserviceController { 8 | constructor( 9 | @Inject('NATS_SERVICE') private natsClient: ClientProxy, 10 | private paymentsService: PaymentsService, 11 | ) {} 12 | @EventPattern('createPayment') 13 | async createPayment(@Payload() createPaymentDto: CreatePaymentDto) { 14 | console.log(createPaymentDto); 15 | const newPayment = 16 | await this.paymentsService.createPayment(createPaymentDto); 17 | if (newPayment) this.natsClient.emit('paymentCreated', newPayment); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /payments-microservice/src/payments/payments.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { PaymentsMicroserviceController } from './payments.controller'; 3 | import { NatsClientModule } from 'src/nats-client/nats-client.module'; 4 | import { PaymentsService } from './payments.service'; 5 | import { TypeOrmModule } from '@nestjs/typeorm'; 6 | import { Payment } from 'src/typeorm/entities/Payment'; 7 | import { User } from 'src/typeorm/entities/User'; 8 | 9 | @Module({ 10 | imports: [TypeOrmModule.forFeature([Payment, User]), NatsClientModule], 11 | controllers: [PaymentsMicroserviceController], 12 | providers: [PaymentsService], 13 | }) 14 | export class PaymentsModule {} 15 | -------------------------------------------------------------------------------- /payments-microservice/src/payments/payments.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, Inject } from '@nestjs/common'; 2 | import { InjectRepository } from '@nestjs/typeorm'; 3 | import { Payment } from 'src/typeorm/entities/Payment'; 4 | import { Repository } from 'typeorm'; 5 | import { CreatePaymentDto } from './dtos/CreatePayment.dto'; 6 | import { ClientProxy } from '@nestjs/microservices'; 7 | import { lastValueFrom } from 'rxjs'; 8 | import { User } from 'src/typeorm/entities/User'; 9 | 10 | @Injectable() 11 | export class PaymentsService { 12 | constructor( 13 | @InjectRepository(Payment) private paymentsRepository: Repository, 14 | @Inject('NATS_SERVICE') private natsClient: ClientProxy, 15 | ) {} 16 | 17 | async createPayment({ userId, ...createPaymentDto }: CreatePaymentDto) { 18 | const user = await lastValueFrom( 19 | this.natsClient.send({ cmd: 'getUserById' }, { userId }), 20 | ); 21 | console.log(user); 22 | if (user) { 23 | const newPayment = this.paymentsRepository.create({ 24 | ...createPaymentDto, 25 | user, 26 | }); 27 | console.log(newPayment); 28 | return this.paymentsRepository.save(newPayment); 29 | } 30 | return null; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /payments-microservice/src/typeorm/entities/Payment.ts: -------------------------------------------------------------------------------- 1 | import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from 'typeorm'; 2 | import { User } from './User'; 3 | 4 | @Entity({ name: 'payments' }) 5 | export class Payment { 6 | @PrimaryGeneratedColumn('uuid') 7 | id: string; 8 | 9 | @Column('float') 10 | amount: number; 11 | 12 | @ManyToOne(() => User, (user) => user.payments) 13 | user: User; 14 | } 15 | -------------------------------------------------------------------------------- /payments-microservice/src/typeorm/entities/User.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Entity, 3 | PrimaryGeneratedColumn, 4 | Column, 5 | OneToMany, 6 | JoinColumn, 7 | } from 'typeorm'; 8 | import { Payment } from './Payment'; 9 | 10 | @Entity({ name: 'users' }) 11 | export class User { 12 | @PrimaryGeneratedColumn('uuid') 13 | id: string; 14 | 15 | @Column({ nullable: false }) 16 | username: string; 17 | 18 | @Column({ nullable: false }) 19 | email: string; 20 | 21 | @Column({ nullable: true }) 22 | displayName?: string; 23 | 24 | @OneToMany(() => Payment, (payment) => payment.user) 25 | @JoinColumn() 26 | payments: Payment[]; 27 | } 28 | -------------------------------------------------------------------------------- /payments-microservice/test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { INestApplication } from '@nestjs/common'; 3 | import * as request from 'supertest'; 4 | import { AppModule } from './../src/app.module'; 5 | 6 | describe('AppController (e2e)', () => { 7 | let app: INestApplication; 8 | 9 | beforeEach(async () => { 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ 11 | imports: [AppModule], 12 | }).compile(); 13 | 14 | app = moduleFixture.createNestApplication(); 15 | await app.init(); 16 | }); 17 | 18 | it('/ (GET)', () => { 19 | return request(app.getHttpServer()) 20 | .get('/') 21 | .expect(200) 22 | .expect('Hello World!'); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /payments-microservice/test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /payments-microservice/tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /payments-microservice/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "target": "ES2021", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./", 13 | "incremental": true, 14 | "skipLibCheck": true, 15 | "strictNullChecks": false, 16 | "noImplicitAny": false, 17 | "strictBindCallApply": false, 18 | "forceConsistentCasingInFileNames": false, 19 | "noFallthroughCasesInSwitch": false 20 | }, 21 | "watchOptions": { 22 | // Use a dynamic polling instead of system’s native events for file changes. 23 | "watchFile": "dynamicPriorityPolling", 24 | "watchDirectory": "dynamicPriorityPolling", 25 | "excludeDirectories": ["**/node_modules", "dist"] 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /users-microservice/.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /users-microservice/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | tsconfigRootDir: __dirname, 6 | sourceType: 'module', 7 | }, 8 | plugins: ['@typescript-eslint/eslint-plugin'], 9 | extends: [ 10 | 'plugin:@typescript-eslint/recommended', 11 | 'plugin:prettier/recommended', 12 | ], 13 | root: true, 14 | env: { 15 | node: true, 16 | jest: true, 17 | }, 18 | ignorePatterns: ['.eslintrc.js'], 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': 'off', 22 | '@typescript-eslint/explicit-module-boundary-types': 'off', 23 | '@typescript-eslint/no-explicit-any': 'off', 24 | }, 25 | }; 26 | -------------------------------------------------------------------------------- /users-microservice/.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | pnpm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # OS 15 | .DS_Store 16 | 17 | # Tests 18 | /coverage 19 | /.nyc_output 20 | 21 | # IDEs and editors 22 | /.idea 23 | .project 24 | .classpath 25 | .c9/ 26 | *.launch 27 | .settings/ 28 | *.sublime-workspace 29 | 30 | # IDE - VSCode 31 | .vscode/* 32 | !.vscode/settings.json 33 | !.vscode/tasks.json 34 | !.vscode/launch.json 35 | !.vscode/extensions.json -------------------------------------------------------------------------------- /users-microservice/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /users-microservice/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:18 2 | 3 | WORKDIR /usr/src/app 4 | 5 | COPY package.json ./ 6 | COPY package-lock.json ./ 7 | 8 | RUN npm install 9 | 10 | COPY . . 11 | -------------------------------------------------------------------------------- /users-microservice/README.md: -------------------------------------------------------------------------------- 1 |

2 | Nest Logo 3 |

4 | 5 | [circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456 6 | [circleci-url]: https://circleci.com/gh/nestjs/nest 7 | 8 |

A progressive Node.js framework for building efficient and scalable server-side applications.

9 |

10 | NPM Version 11 | Package License 12 | NPM Downloads 13 | CircleCI 14 | Coverage 15 | Discord 16 | Backers on Open Collective 17 | Sponsors on Open Collective 18 | 19 | Support us 20 | 21 |

22 | 24 | 25 | ## Description 26 | 27 | [Nest](https://github.com/nestjs/nest) framework TypeScript starter repository. 28 | 29 | ## Installation 30 | 31 | ```bash 32 | $ npm install 33 | ``` 34 | 35 | ## Running the app 36 | 37 | ```bash 38 | # development 39 | $ npm run start 40 | 41 | # watch mode 42 | $ npm run start:dev 43 | 44 | # production mode 45 | $ npm run start:prod 46 | ``` 47 | 48 | ## Test 49 | 50 | ```bash 51 | # unit tests 52 | $ npm run test 53 | 54 | # e2e tests 55 | $ npm run test:e2e 56 | 57 | # test coverage 58 | $ npm run test:cov 59 | ``` 60 | 61 | ## Support 62 | 63 | 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). 64 | 65 | ## Stay in touch 66 | 67 | - Author - [Kamil Myśliwiec](https://kamilmysliwiec.com) 68 | - Website - [https://nestjs.com](https://nestjs.com/) 69 | - Twitter - [@nestframework](https://twitter.com/nestframework) 70 | 71 | ## License 72 | 73 | Nest is [MIT licensed](LICENSE). 74 | -------------------------------------------------------------------------------- /users-microservice/nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/nest-cli", 3 | "collection": "@nestjs/schematics", 4 | "sourceRoot": "src", 5 | "compilerOptions": { 6 | "deleteOutDir": true 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /users-microservice/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "users-microservice", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "build": "nest build", 10 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 11 | "start": "nest start", 12 | "start:dev": "nest start --watch", 13 | "start:debug": "nest start --debug --watch", 14 | "start:prod": "node dist/main", 15 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 16 | "test": "jest", 17 | "test:watch": "jest --watch", 18 | "test:cov": "jest --coverage", 19 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 20 | "test:e2e": "jest --config ./test/jest-e2e.json" 21 | }, 22 | "dependencies": { 23 | "@nestjs/common": "^10.0.0", 24 | "@nestjs/core": "^10.0.0", 25 | "@nestjs/microservices": "^10.2.10", 26 | "@nestjs/platform-express": "^10.0.0", 27 | "@nestjs/typeorm": "^10.0.1", 28 | "mysql2": "^3.6.5", 29 | "nats": "^2.18.0", 30 | "reflect-metadata": "^0.1.13", 31 | "rxjs": "^7.8.1", 32 | "typeorm": "^0.3.17" 33 | }, 34 | "devDependencies": { 35 | "@nestjs/cli": "^10.0.0", 36 | "@nestjs/schematics": "^10.0.0", 37 | "@nestjs/testing": "^10.0.0", 38 | "@types/express": "^4.17.17", 39 | "@types/jest": "^29.5.2", 40 | "@types/node": "^20.3.1", 41 | "@types/supertest": "^2.0.12", 42 | "@typescript-eslint/eslint-plugin": "^6.0.0", 43 | "@typescript-eslint/parser": "^6.0.0", 44 | "eslint": "^8.42.0", 45 | "eslint-config-prettier": "^9.0.0", 46 | "eslint-plugin-prettier": "^5.0.0", 47 | "jest": "^29.5.0", 48 | "prettier": "^3.0.0", 49 | "source-map-support": "^0.5.21", 50 | "supertest": "^6.3.3", 51 | "ts-jest": "^29.1.0", 52 | "ts-loader": "^9.4.3", 53 | "ts-node": "^10.9.1", 54 | "tsconfig-paths": "^4.2.0", 55 | "typescript": "^5.1.3" 56 | }, 57 | "jest": { 58 | "moduleFileExtensions": [ 59 | "js", 60 | "json", 61 | "ts" 62 | ], 63 | "rootDir": "src", 64 | "testRegex": ".*\\.spec\\.ts$", 65 | "transform": { 66 | "^.+\\.(t|j)s$": "ts-jest" 67 | }, 68 | "collectCoverageFrom": [ 69 | "**/*.(t|j)s" 70 | ], 71 | "coverageDirectory": "../coverage", 72 | "testEnvironment": "node" 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /users-microservice/src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { UsersModule } from './users/users.module'; 3 | import { TypeOrmModule } from '@nestjs/typeorm'; 4 | import { User } from './typeorm/entities/User'; 5 | import { Payment } from './typeorm/entities/Payment'; 6 | 7 | @Module({ 8 | imports: [ 9 | TypeOrmModule.forRoot({ 10 | type: 'mysql', 11 | host: 'mysql_db', 12 | port: 3307, 13 | database: 'nestjs_db', 14 | entities: [User, Payment], 15 | synchronize: true, 16 | username: 'testuser', 17 | password: 'testuser123', 18 | }), 19 | UsersModule, 20 | ], 21 | controllers: [], 22 | providers: [], 23 | }) 24 | export class AppModule {} 25 | -------------------------------------------------------------------------------- /users-microservice/src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | import { MicroserviceOptions, Transport } from '@nestjs/microservices'; 4 | 5 | async function bootstrap() { 6 | console.log('Users Microservice is Running!'); 7 | const app = await NestFactory.createMicroservice( 8 | AppModule, 9 | { 10 | transport: Transport.NATS, 11 | options: { 12 | servers: ['nats://nats'], 13 | }, 14 | }, 15 | ); 16 | await app.listen(); 17 | } 18 | bootstrap(); 19 | -------------------------------------------------------------------------------- /users-microservice/src/typeorm/entities/Payment.ts: -------------------------------------------------------------------------------- 1 | import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from 'typeorm'; 2 | import { User } from './User'; 3 | 4 | @Entity({ name: 'payments' }) 5 | export class Payment { 6 | @PrimaryGeneratedColumn('uuid') 7 | id: string; 8 | 9 | @Column('float') 10 | amount: number; 11 | 12 | @ManyToOne(() => User, (user) => user.payments) 13 | user: User; 14 | } 15 | -------------------------------------------------------------------------------- /users-microservice/src/typeorm/entities/User.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Entity, 3 | PrimaryGeneratedColumn, 4 | Column, 5 | OneToMany, 6 | JoinColumn, 7 | } from 'typeorm'; 8 | import { Payment } from './Payment'; 9 | 10 | @Entity({ name: 'users' }) 11 | export class User { 12 | @PrimaryGeneratedColumn('uuid') 13 | id: string; 14 | 15 | @Column({ nullable: false }) 16 | username: string; 17 | 18 | @Column({ nullable: false }) 19 | email: string; 20 | 21 | @Column({ nullable: true }) 22 | displayName?: string; 23 | 24 | @OneToMany(() => Payment, (payment) => payment.user) 25 | @JoinColumn() 26 | payments: Payment[]; 27 | } 28 | -------------------------------------------------------------------------------- /users-microservice/src/users/dtos/CreateUser.dto.ts: -------------------------------------------------------------------------------- 1 | export class CreateUserDto { 2 | username: string; 3 | 4 | displayName?: string; 5 | 6 | email: string; 7 | } 8 | -------------------------------------------------------------------------------- /users-microservice/src/users/users.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller } from '@nestjs/common'; 2 | import { EventPattern, MessagePattern, Payload } from '@nestjs/microservices'; 3 | import { CreateUserDto } from './dtos/CreateUser.dto'; 4 | import { UsersService } from './users.service'; 5 | 6 | @Controller() 7 | export class UsersMicroserviceController { 8 | constructor(private usersService: UsersService) {} 9 | @MessagePattern({ cmd: 'createUser' }) 10 | createUser(@Payload() data: CreateUserDto) { 11 | return this.usersService.createUser(data); 12 | } 13 | 14 | @MessagePattern({ cmd: 'getUserById' }) 15 | getUserById(@Payload() data) { 16 | const { userId } = data; 17 | return this.usersService.getUserById(userId); 18 | } 19 | 20 | @EventPattern('paymentCreated') 21 | paymentCreated(@Payload() data: any) { 22 | console.log(data); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /users-microservice/src/users/users.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | import { UsersMicroserviceController } from './users.controller'; 4 | import { UsersService } from './users.service'; 5 | import { User } from 'src/typeorm/entities/User'; 6 | import { Payment } from 'src/typeorm/entities/Payment'; 7 | 8 | @Module({ 9 | imports: [TypeOrmModule.forFeature([User, Payment])], 10 | controllers: [UsersMicroserviceController], 11 | providers: [UsersService], 12 | }) 13 | export class UsersModule {} 14 | -------------------------------------------------------------------------------- /users-microservice/src/users/users.service.ts: -------------------------------------------------------------------------------- 1 | import { InjectRepository } from '@nestjs/typeorm'; 2 | import { Repository } from 'typeorm'; 3 | import { User } from 'src/typeorm/entities/User'; 4 | import { Injectable } from '@nestjs/common'; 5 | import { CreateUserDto } from './dtos/CreateUser.dto'; 6 | 7 | @Injectable() 8 | export class UsersService { 9 | constructor( 10 | @InjectRepository(User) private usersRepository: Repository, 11 | ) {} 12 | 13 | createUser(createUserDto: CreateUserDto) { 14 | const newUser = this.usersRepository.create(createUserDto); 15 | return this.usersRepository.save(newUser); 16 | } 17 | 18 | getUserById(userId: string) { 19 | return this.usersRepository.findOne({ 20 | where: { id: userId }, 21 | relations: ['payments'], 22 | }); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /users-microservice/test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { INestApplication } from '@nestjs/common'; 3 | import * as request from 'supertest'; 4 | import { AppModule } from './../src/app.module'; 5 | 6 | describe('AppController (e2e)', () => { 7 | let app: INestApplication; 8 | 9 | beforeEach(async () => { 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ 11 | imports: [AppModule], 12 | }).compile(); 13 | 14 | app = moduleFixture.createNestApplication(); 15 | await app.init(); 16 | }); 17 | 18 | it('/ (GET)', () => { 19 | return request(app.getHttpServer()) 20 | .get('/') 21 | .expect(200) 22 | .expect('Hello World!'); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /users-microservice/test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /users-microservice/tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /users-microservice/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "target": "ES2021", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./", 13 | "incremental": true, 14 | "skipLibCheck": true, 15 | "strictNullChecks": false, 16 | "noImplicitAny": false, 17 | "strictBindCallApply": false, 18 | "forceConsistentCasingInFileNames": false, 19 | "noFallthroughCasesInSwitch": false 20 | }, 21 | "watchOptions": { 22 | // Use a dynamic polling instead of system’s native events for file changes. 23 | "watchFile": "dynamicPriorityPolling", 24 | "watchDirectory": "dynamicPriorityPolling", 25 | "excludeDirectories": ["**/node_modules", "dist"] 26 | } 27 | } 28 | --------------------------------------------------------------------------------