├── .dockerignore
├── .eslintrc.js
├── .gitignore
├── .prettierrc
├── README.md
├── apps
├── auth
│ ├── .env
│ ├── Dockerfile
│ ├── src
│ │ ├── auth.controller.ts
│ │ ├── auth.module.ts
│ │ ├── auth.service.spec.ts
│ │ ├── auth.service.ts
│ │ ├── current-user.decorator.ts
│ │ ├── guards
│ │ │ ├── jwt-auth.guard.ts
│ │ │ └── local-auth.guard.ts
│ │ ├── main.ts
│ │ ├── strategies
│ │ │ ├── jwt.strategy.ts
│ │ │ └── local.strategy.ts
│ │ └── users
│ │ │ ├── dto
│ │ │ └── create-user.request.ts
│ │ │ ├── schemas
│ │ │ └── user.schema.ts
│ │ │ ├── users.controller.ts
│ │ │ ├── users.module.ts
│ │ │ ├── users.repository.ts
│ │ │ └── users.service.ts
│ ├── test
│ │ ├── app.e2e-spec.ts
│ │ └── jest-e2e.json
│ └── tsconfig.app.json
├── billing
│ ├── .env
│ ├── Dockerfile
│ ├── src
│ │ ├── billing.controller.spec.ts
│ │ ├── billing.controller.ts
│ │ ├── billing.module.ts
│ │ ├── billing.service.ts
│ │ └── main.ts
│ ├── test
│ │ ├── app.e2e-spec.ts
│ │ └── jest-e2e.json
│ └── tsconfig.app.json
└── orders
│ ├── .env
│ ├── Dockerfile
│ ├── src
│ ├── constants
│ │ └── services.ts
│ ├── dto
│ │ └── create-order.request.ts
│ ├── main.ts
│ ├── orders.controller.spec.ts
│ ├── orders.controller.ts
│ ├── orders.module.ts
│ ├── orders.repository.ts
│ ├── orders.service.ts
│ └── schemas
│ │ └── order.schema.ts
│ ├── test
│ ├── app.e2e-spec.ts
│ └── jest-e2e.json
│ └── tsconfig.app.json
├── docker-compose.yml
├── libs
└── common
│ ├── src
│ ├── auth
│ │ ├── auth.module.ts
│ │ ├── jwt-auth.guard.ts
│ │ └── services.ts
│ ├── database
│ │ ├── abstract.repository.ts
│ │ ├── abstract.schema.ts
│ │ └── database.module.ts
│ ├── index.ts
│ └── rmq
│ │ ├── rmq.module.ts
│ │ └── rmq.service.ts
│ └── tsconfig.lib.json
├── nest-cli.json
├── package-lock.json
├── package.json
├── tsconfig.build.json
└── tsconfig.json
/.dockerignore:
--------------------------------------------------------------------------------
1 | # Versioning and metadata
2 | .git
3 | .gitignore
4 | .dockerignore
5 |
6 | # Build dependencies
7 | dist.do
8 | node_modules
9 |
10 | # Environment (contains sensitive data)
11 | *.env
12 |
13 | # Misc
14 | .eslintrc.js
15 | .prettierrc
16 | README.md
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | parser: '@typescript-eslint/parser',
3 | parserOptions: {
4 | project: 'tsconfig.json',
5 | sourceType: 'module',
6 | },
7 | plugins: ['@typescript-eslint/eslint-plugin'],
8 | extends: [
9 | 'plugin:@typescript-eslint/recommended',
10 | 'plugin:prettier/recommended',
11 | ],
12 | root: true,
13 | env: {
14 | node: true,
15 | jest: true,
16 | },
17 | ignorePatterns: ['.eslintrc.js'],
18 | rules: {
19 | '@typescript-eslint/interface-name-prefix': 'off',
20 | '@typescript-eslint/explicit-function-return-type': 'off',
21 | '@typescript-eslint/explicit-module-boundary-types': 'off',
22 | '@typescript-eslint/no-explicit-any': 'off',
23 | },
24 | };
25 |
--------------------------------------------------------------------------------
/.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
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "singleQuote": true,
3 | "trailingComma": "all"
4 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
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 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
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 |
--------------------------------------------------------------------------------
/apps/auth/.env:
--------------------------------------------------------------------------------
1 | PORT=3001
2 |
3 | JWT_EXPIRATION=3600
4 | JWT_SECRET=yJSDVpxKUQ1LSfrnrsLN6r6tmFd1i95I3zGXjpIryO8zoWg7fDmYEnyyCmtKFh2MFd4c7rFjN9wKsiwRXYKZ9BKJ5YHTByQi8Q4
5 |
6 | MONGODB_URI=mongodb://root:password123@mongodb-primary:27017/
7 |
8 | RABBIT_MQ_URI=amqp://rabbitmq:5672
9 | RABBIT_MQ_AUTH_QUEUE=auth
--------------------------------------------------------------------------------
/apps/auth/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM node:alpine As development
2 |
3 | WORKDIR /usr/src/app
4 |
5 | COPY package*.json ./
6 |
7 | RUN npm install
8 |
9 | COPY . .
10 |
11 | RUN npm run build auth
12 |
13 | FROM node:alpine as production
14 |
15 | ARG NODE_ENV=production
16 | ENV NODE_ENV=${NODE_ENV}
17 |
18 | WORKDIR /usr/src/app
19 |
20 | COPY package*.json ./
21 |
22 | RUN npm install --only=production
23 |
24 | COPY . .
25 |
26 | COPY --from=development /usr/src/app/dist ./dist
27 |
28 | CMD ["node", "dist/apps/auth/main"]
--------------------------------------------------------------------------------
/apps/auth/src/auth.controller.ts:
--------------------------------------------------------------------------------
1 | import { Controller, Post, Res, UseGuards } from '@nestjs/common';
2 | import { MessagePattern } from '@nestjs/microservices';
3 | import { Response } from 'express';
4 | import { AuthService } from './auth.service';
5 | import { CurrentUser } from './current-user.decorator';
6 | import JwtAuthGuard from './guards/jwt-auth.guard';
7 | import { LocalAuthGuard } from './guards/local-auth.guard';
8 | import { User } from './users/schemas/user.schema';
9 |
10 | @Controller('auth')
11 | export class AuthController {
12 | constructor(private readonly authService: AuthService) {}
13 |
14 | @UseGuards(LocalAuthGuard)
15 | @Post('login')
16 | async login(
17 | @CurrentUser() user: User,
18 | @Res({ passthrough: true }) response: Response,
19 | ) {
20 | await this.authService.login(user, response);
21 | response.send(user);
22 | }
23 |
24 | @UseGuards(JwtAuthGuard)
25 | @MessagePattern('validate_user')
26 | async validateUser(@CurrentUser() user: User) {
27 | return user;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/apps/auth/src/auth.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { ConfigModule, ConfigService } from '@nestjs/config';
3 | import { JwtModule } from '@nestjs/jwt';
4 | import { RmqModule, DatabaseModule } from '@app/common';
5 | import * as Joi from 'joi';
6 | import { AuthController } from './auth.controller';
7 | import { AuthService } from './auth.service';
8 | import { JwtStrategy } from './strategies/jwt.strategy';
9 | import { LocalStrategy } from './strategies/local.strategy';
10 | import { UsersModule } from './users/users.module';
11 |
12 | @Module({
13 | imports: [
14 | DatabaseModule,
15 | UsersModule,
16 | RmqModule,
17 | ConfigModule.forRoot({
18 | isGlobal: true,
19 | validationSchema: Joi.object({
20 | JWT_SECRET: Joi.string().required(),
21 | JWT_EXPIRATION: Joi.string().required(),
22 | MONGODB_URI: Joi.string().required(),
23 | }),
24 | envFilePath: './apps/auth/.env',
25 | }),
26 | JwtModule.registerAsync({
27 | useFactory: (configService: ConfigService) => ({
28 | secret: configService.get('JWT_SECRET'),
29 | signOptions: {
30 | expiresIn: `${configService.get('JWT_EXPIRATION')}s`,
31 | },
32 | }),
33 | inject: [ConfigService],
34 | }),
35 | ],
36 | controllers: [AuthController],
37 | providers: [AuthService, LocalStrategy, JwtStrategy],
38 | })
39 | export class AuthModule {}
40 |
--------------------------------------------------------------------------------
/apps/auth/src/auth.service.spec.ts:
--------------------------------------------------------------------------------
1 | import { Test, TestingModule } from '@nestjs/testing';
2 | import { AuthService } from './auth.service';
3 |
4 | describe('AuthService', () => {
5 | let service: AuthService;
6 |
7 | beforeEach(async () => {
8 | const module: TestingModule = await Test.createTestingModule({
9 | providers: [AuthService],
10 | }).compile();
11 |
12 | service = module.get(AuthService);
13 | });
14 |
15 | it('should be defined', () => {
16 | expect(service).toBeDefined();
17 | });
18 | });
19 |
--------------------------------------------------------------------------------
/apps/auth/src/auth.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@nestjs/common';
2 | import { ConfigService } from '@nestjs/config';
3 | import { JwtService } from '@nestjs/jwt';
4 | import { Response } from 'express';
5 | import { User } from './users/schemas/user.schema';
6 |
7 | export interface TokenPayload {
8 | userId: string;
9 | }
10 |
11 | @Injectable()
12 | export class AuthService {
13 | constructor(
14 | private readonly configService: ConfigService,
15 | private readonly jwtService: JwtService,
16 | ) {}
17 |
18 | async login(user: User, response: Response) {
19 | const tokenPayload: TokenPayload = {
20 | userId: user._id.toHexString(),
21 | };
22 |
23 | const expires = new Date();
24 | expires.setSeconds(
25 | expires.getSeconds() + this.configService.get('JWT_EXPIRATION'),
26 | );
27 |
28 | const token = this.jwtService.sign(tokenPayload);
29 |
30 | response.cookie('Authentication', token, {
31 | httpOnly: true,
32 | expires,
33 | });
34 | }
35 |
36 | logout(response: Response) {
37 | response.cookie('Authentication', '', {
38 | httpOnly: true,
39 | expires: new Date(),
40 | });
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/apps/auth/src/current-user.decorator.ts:
--------------------------------------------------------------------------------
1 | import { createParamDecorator, ExecutionContext } from '@nestjs/common';
2 | import { User } from './users/schemas/user.schema';
3 |
4 | export const getCurrentUserByContext = (context: ExecutionContext): User => {
5 | if (context.getType() === 'http') {
6 | return context.switchToHttp().getRequest().user;
7 | }
8 | if (context.getType() === 'rpc') {
9 | return context.switchToRpc().getData().user;
10 | }
11 | };
12 |
13 | export const CurrentUser = createParamDecorator(
14 | (_data: unknown, context: ExecutionContext) =>
15 | getCurrentUserByContext(context),
16 | );
17 |
--------------------------------------------------------------------------------
/apps/auth/src/guards/jwt-auth.guard.ts:
--------------------------------------------------------------------------------
1 | import { AuthGuard } from '@nestjs/passport';
2 |
3 | export default class JwtAuthGuard extends AuthGuard('jwt') {}
4 |
--------------------------------------------------------------------------------
/apps/auth/src/guards/local-auth.guard.ts:
--------------------------------------------------------------------------------
1 | import { AuthGuard } from '@nestjs/passport';
2 |
3 | export class LocalAuthGuard extends AuthGuard('local') {}
4 |
--------------------------------------------------------------------------------
/apps/auth/src/main.ts:
--------------------------------------------------------------------------------
1 | import { NestFactory } from '@nestjs/core';
2 | import { RmqService } from '@app/common';
3 | import { AuthModule } from './auth.module';
4 | import { RmqOptions } from '@nestjs/microservices';
5 | import { ValidationPipe } from '@nestjs/common';
6 | import { ConfigService } from '@nestjs/config';
7 |
8 | async function bootstrap() {
9 | const app = await NestFactory.create(AuthModule);
10 | const rmqService = app.get(RmqService);
11 | app.connectMicroservice(rmqService.getOptions('AUTH', true));
12 | app.useGlobalPipes(new ValidationPipe());
13 | const configService = app.get(ConfigService);
14 | await app.startAllMicroservices();
15 | await app.listen(configService.get('PORT'));
16 | }
17 | bootstrap();
18 |
--------------------------------------------------------------------------------
/apps/auth/src/strategies/jwt.strategy.ts:
--------------------------------------------------------------------------------
1 | import { Injectable, UnauthorizedException } from '@nestjs/common';
2 | import { ConfigService } from '@nestjs/config';
3 | import { PassportStrategy } from '@nestjs/passport';
4 | import { ExtractJwt, Strategy } from 'passport-jwt';
5 | import { Types } from 'mongoose';
6 | import { TokenPayload } from '../auth.service';
7 | import { UsersService } from '../users/users.service';
8 |
9 | @Injectable()
10 | export class JwtStrategy extends PassportStrategy(Strategy) {
11 | constructor(
12 | configService: ConfigService,
13 | private readonly usersService: UsersService,
14 | ) {
15 | super({
16 | jwtFromRequest: ExtractJwt.fromExtractors([
17 | (request: any) => {
18 | return request?.Authentication;
19 | },
20 | ]),
21 | secretOrKey: configService.get('JWT_SECRET'),
22 | });
23 | }
24 |
25 | async validate({ userId }: TokenPayload) {
26 | try {
27 | return await this.usersService.getUser({
28 | _id: new Types.ObjectId(userId),
29 | });
30 | } catch (err) {
31 | throw new UnauthorizedException();
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/apps/auth/src/strategies/local.strategy.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@nestjs/common';
2 | import { PassportStrategy } from '@nestjs/passport';
3 | import { Strategy } from 'passport-local';
4 | import { UsersService } from '../users/users.service';
5 |
6 | @Injectable()
7 | export class LocalStrategy extends PassportStrategy(Strategy) {
8 | constructor(private readonly usersService: UsersService) {
9 | super({ usernameField: 'email' });
10 | }
11 |
12 | async validate(email: string, password: string) {
13 | return this.usersService.validateUser(email, password);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/apps/auth/src/users/dto/create-user.request.ts:
--------------------------------------------------------------------------------
1 | import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
2 |
3 | export class CreateUserRequest {
4 | @IsEmail()
5 | email: string;
6 |
7 | @IsString()
8 | @IsNotEmpty()
9 | password: string;
10 | }
11 |
--------------------------------------------------------------------------------
/apps/auth/src/users/schemas/user.schema.ts:
--------------------------------------------------------------------------------
1 | import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
2 | import { AbstractDocument } from '@app/common';
3 |
4 | @Schema({ versionKey: false })
5 | export class User extends AbstractDocument {
6 | @Prop()
7 | email: string;
8 |
9 | @Prop()
10 | password: string;
11 | }
12 |
13 | export const UserSchema = SchemaFactory.createForClass(User);
14 |
--------------------------------------------------------------------------------
/apps/auth/src/users/users.controller.ts:
--------------------------------------------------------------------------------
1 | import { Body, Controller, Post } from '@nestjs/common';
2 | import { CreateUserRequest } from './dto/create-user.request';
3 | import { UsersService } from './users.service';
4 |
5 | @Controller('auth/users')
6 | export class UsersController {
7 | constructor(private readonly usersService: UsersService) {}
8 |
9 | @Post()
10 | async createUser(@Body() request: CreateUserRequest) {
11 | return this.usersService.createUser(request);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/apps/auth/src/users/users.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { UsersRepository } from './users.repository';
3 | import { UsersController } from './users.controller';
4 | import { UsersService } from './users.service';
5 | import { MongooseModule } from '@nestjs/mongoose';
6 | import { User, UserSchema } from './schemas/user.schema';
7 |
8 | @Module({
9 | imports: [
10 | MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
11 | ],
12 | controllers: [UsersController],
13 | providers: [UsersService, UsersRepository],
14 | exports: [UsersService],
15 | })
16 | export class UsersModule {}
17 |
--------------------------------------------------------------------------------
/apps/auth/src/users/users.repository.ts:
--------------------------------------------------------------------------------
1 | import { Injectable, Logger } from '@nestjs/common';
2 | import { InjectConnection, InjectModel } from '@nestjs/mongoose';
3 | import { Model, Connection } from 'mongoose';
4 | import { AbstractRepository } from '@app/common';
5 | import { User } from './schemas/user.schema';
6 |
7 | @Injectable()
8 | export class UsersRepository extends AbstractRepository {
9 | protected readonly logger = new Logger(UsersRepository.name);
10 |
11 | constructor(
12 | @InjectModel(User.name) userModel: Model,
13 | @InjectConnection() connection: Connection,
14 | ) {
15 | super(userModel, connection);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/apps/auth/src/users/users.service.ts:
--------------------------------------------------------------------------------
1 | import {
2 | Injectable,
3 | UnauthorizedException,
4 | UnprocessableEntityException,
5 | } from '@nestjs/common';
6 | import * as bcrypt from 'bcrypt';
7 | import { UsersRepository } from './users.repository';
8 | import { CreateUserRequest } from './dto/create-user.request';
9 | import { User } from './schemas/user.schema';
10 |
11 | @Injectable()
12 | export class UsersService {
13 | constructor(private readonly usersRepository: UsersRepository) {}
14 |
15 | async createUser(request: CreateUserRequest) {
16 | await this.validateCreateUserRequest(request);
17 | const user = await this.usersRepository.create({
18 | ...request,
19 | password: await bcrypt.hash(request.password, 10),
20 | });
21 | return user;
22 | }
23 |
24 | private async validateCreateUserRequest(request: CreateUserRequest) {
25 | let user: User;
26 | try {
27 | user = await this.usersRepository.findOne({
28 | email: request.email,
29 | });
30 | } catch (err) {}
31 |
32 | if (user) {
33 | throw new UnprocessableEntityException('Email already exists.');
34 | }
35 | }
36 |
37 | async validateUser(email: string, password: string) {
38 | const user = await this.usersRepository.findOne({ email });
39 | const passwordIsValid = await bcrypt.compare(password, user.password);
40 | if (!passwordIsValid) {
41 | throw new UnauthorizedException('Credentials are not valid.');
42 | }
43 | return user;
44 | }
45 |
46 | async getUser(getUserArgs: Partial) {
47 | return this.usersRepository.findOne(getUserArgs);
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/apps/auth/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 { AuthModule } from './../src/auth.module';
5 |
6 | describe('AuthController (e2e)', () => {
7 | let app: INestApplication;
8 |
9 | beforeEach(async () => {
10 | const moduleFixture: TestingModule = await Test.createTestingModule({
11 | imports: [AuthModule],
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 |
--------------------------------------------------------------------------------
/apps/auth/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 |
--------------------------------------------------------------------------------
/apps/auth/tsconfig.app.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tsconfig.json",
3 | "compilerOptions": {
4 | "declaration": false,
5 | "outDir": "../../dist/apps/auth"
6 | },
7 | "include": ["src/**/*"],
8 | "exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
9 | }
10 |
--------------------------------------------------------------------------------
/apps/billing/.env:
--------------------------------------------------------------------------------
1 | RABBIT_MQ_URI=amqp://rabbitmq:5672
2 | RABBIT_MQ_BILLING_QUEUE=billing
3 | RABBIT_MQ_AUTH_QUEUE=auth
--------------------------------------------------------------------------------
/apps/billing/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM node:alpine As development
2 |
3 | WORKDIR /usr/src/app
4 |
5 | COPY package*.json ./
6 |
7 | RUN npm install
8 |
9 | COPY . .
10 |
11 | RUN npm run build billing
12 |
13 | FROM node:alpine as production
14 |
15 | ARG NODE_ENV=production
16 | ENV NODE_ENV=${NODE_ENV}
17 |
18 | WORKDIR /usr/src/app
19 |
20 | COPY package*.json ./
21 |
22 | RUN npm install --only=production
23 |
24 | COPY . .
25 |
26 | COPY --from=development /usr/src/app/dist ./dist
27 |
28 | CMD ["node", "dist/apps/billing/main"]
--------------------------------------------------------------------------------
/apps/billing/src/billing.controller.spec.ts:
--------------------------------------------------------------------------------
1 | import { Test, TestingModule } from '@nestjs/testing';
2 | import { BillingController } from './billing.controller';
3 | import { BillingService } from './billing.service';
4 |
5 | describe('BillingController', () => {
6 | let billingController: BillingController;
7 |
8 | beforeEach(async () => {
9 | const app: TestingModule = await Test.createTestingModule({
10 | controllers: [BillingController],
11 | providers: [BillingService],
12 | }).compile();
13 |
14 | billingController = app.get(BillingController);
15 | });
16 |
17 | describe('root', () => {
18 | it('should return "Hello World!"', () => {
19 | expect(billingController.getHello()).toBe('Hello World!');
20 | });
21 | });
22 | });
23 |
--------------------------------------------------------------------------------
/apps/billing/src/billing.controller.ts:
--------------------------------------------------------------------------------
1 | import { Controller, Get, UseGuards } from '@nestjs/common';
2 | import { Ctx, EventPattern, Payload, RmqContext } from '@nestjs/microservices';
3 | import { RmqService, JwtAuthGuard } from '@app/common';
4 | import { BillingService } from './billing.service';
5 |
6 | @Controller()
7 | export class BillingController {
8 | constructor(
9 | private readonly billingService: BillingService,
10 | private readonly rmqService: RmqService,
11 | ) {}
12 |
13 | @Get()
14 | getHello(): string {
15 | return this.billingService.getHello();
16 | }
17 |
18 | @EventPattern('order_created')
19 | @UseGuards(JwtAuthGuard)
20 | async handleOrderCreated(@Payload() data: any, @Ctx() context: RmqContext) {
21 | this.billingService.bill(data);
22 | this.rmqService.ack(context);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/apps/billing/src/billing.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { RmqModule, AuthModule } from '@app/common';
3 | import * as Joi from 'joi';
4 | import { BillingController } from './billing.controller';
5 | import { BillingService } from './billing.service';
6 | import { ConfigModule } from '@nestjs/config';
7 |
8 | @Module({
9 | imports: [
10 | ConfigModule.forRoot({
11 | isGlobal: true,
12 | validationSchema: Joi.object({
13 | RABBIT_MQ_URI: Joi.string().required(),
14 | RABBIT_MQ_BILLING_QUEUE: Joi.string().required(),
15 | }),
16 | }),
17 | RmqModule,
18 | AuthModule,
19 | ],
20 | controllers: [BillingController],
21 | providers: [BillingService],
22 | })
23 | export class BillingModule {}
24 |
--------------------------------------------------------------------------------
/apps/billing/src/billing.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable, Logger } from '@nestjs/common';
2 |
3 | @Injectable()
4 | export class BillingService {
5 | private readonly logger = new Logger(BillingService.name);
6 |
7 | getHello(): string {
8 | return 'Hello World!';
9 | }
10 |
11 | bill(data: any) {
12 | this.logger.log('Billing...', data);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/apps/billing/src/main.ts:
--------------------------------------------------------------------------------
1 | import { NestFactory } from '@nestjs/core';
2 | import { RmqService } from '@app/common';
3 | import { BillingModule } from './billing.module';
4 |
5 | async function bootstrap() {
6 | const app = await NestFactory.create(BillingModule);
7 | const rmqService = app.get(RmqService);
8 | app.connectMicroservice(rmqService.getOptions('BILLING'));
9 | await app.startAllMicroservices();
10 | }
11 | bootstrap();
12 |
--------------------------------------------------------------------------------
/apps/billing/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 { BillingModule } from './../src/billing.module';
5 |
6 | describe('BillingController (e2e)', () => {
7 | let app: INestApplication;
8 |
9 | beforeEach(async () => {
10 | const moduleFixture: TestingModule = await Test.createTestingModule({
11 | imports: [BillingModule],
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 |
--------------------------------------------------------------------------------
/apps/billing/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 |
--------------------------------------------------------------------------------
/apps/billing/tsconfig.app.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tsconfig.json",
3 | "compilerOptions": {
4 | "declaration": false,
5 | "outDir": "../../dist/apps/billing"
6 | },
7 | "include": ["src/**/*"],
8 | "exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
9 | }
10 |
--------------------------------------------------------------------------------
/apps/orders/.env:
--------------------------------------------------------------------------------
1 | MONGODB_URI=mongodb://root:password123@mongodb-primary:27017/
2 |
3 | PORT=3000
4 |
5 | RABBIT_MQ_URI=amqp://rabbitmq:5672
6 | RABBIT_MQ_BILLING_QUEUE=billing
7 | RABBIT_MQ_AUTH_QUEUE=auth
--------------------------------------------------------------------------------
/apps/orders/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM node:alpine As development
2 |
3 | WORKDIR /usr/src/app
4 |
5 | COPY package*.json ./
6 |
7 | RUN npm install
8 |
9 | COPY . .
10 |
11 | RUN npm run build
12 |
13 | FROM node:alpine as production
14 |
15 | ARG NODE_ENV=production
16 | ENV NODE_ENV=${NODE_ENV}
17 |
18 | WORKDIR /usr/src/app
19 |
20 | COPY package*.json ./
21 |
22 | RUN npm install --only=production
23 |
24 | COPY . .
25 |
26 | COPY --from=development /usr/src/app/dist ./dist
27 |
28 | CMD ["node", "dist/apps/orders/main"]
--------------------------------------------------------------------------------
/apps/orders/src/constants/services.ts:
--------------------------------------------------------------------------------
1 | export const BILLING_SERVICE = 'BILLING';
2 |
--------------------------------------------------------------------------------
/apps/orders/src/dto/create-order.request.ts:
--------------------------------------------------------------------------------
1 | import {
2 | IsNotEmpty,
3 | IsPhoneNumber,
4 | IsPositive,
5 | IsString,
6 | } from 'class-validator';
7 |
8 | export class CreateOrderRequest {
9 | @IsString()
10 | @IsNotEmpty()
11 | name: string;
12 |
13 | @IsPositive()
14 | price: number;
15 |
16 | @IsPhoneNumber()
17 | phoneNumber: string;
18 | }
19 |
--------------------------------------------------------------------------------
/apps/orders/src/main.ts:
--------------------------------------------------------------------------------
1 | import { ValidationPipe } from '@nestjs/common';
2 | import { ConfigService } from '@nestjs/config';
3 | import { NestFactory } from '@nestjs/core';
4 | import { OrdersModule } from './orders.module';
5 |
6 | async function bootstrap() {
7 | const app = await NestFactory.create(OrdersModule);
8 | app.useGlobalPipes(new ValidationPipe());
9 | const configService = app.get(ConfigService);
10 | await app.listen(configService.get('PORT'));
11 | }
12 | bootstrap();
13 |
--------------------------------------------------------------------------------
/apps/orders/src/orders.controller.spec.ts:
--------------------------------------------------------------------------------
1 | import { Test, TestingModule } from '@nestjs/testing';
2 | import { OrdersController } from './orders.controller';
3 | import { OrdersService } from './orders.service';
4 |
5 | describe('OrdersController', () => {
6 | let ordersController: OrdersController;
7 |
8 | beforeEach(async () => {
9 | const app: TestingModule = await Test.createTestingModule({
10 | controllers: [OrdersController],
11 | providers: [OrdersService],
12 | }).compile();
13 |
14 | ordersController = app.get(OrdersController);
15 | });
16 |
17 | describe('root', () => {
18 | it('should return "Hello World!"', () => {
19 | expect(ordersController.getHello()).toBe('Hello World!');
20 | });
21 | });
22 | });
23 |
--------------------------------------------------------------------------------
/apps/orders/src/orders.controller.ts:
--------------------------------------------------------------------------------
1 | import { Body, Controller, Get, Post, Req, UseGuards } from '@nestjs/common';
2 | import { JwtAuthGuard } from '@app/common';
3 | import { CreateOrderRequest } from './dto/create-order.request';
4 | import { OrdersService } from './orders.service';
5 |
6 | @Controller('orders')
7 | export class OrdersController {
8 | constructor(private readonly ordersService: OrdersService) {}
9 |
10 | @Post()
11 | @UseGuards(JwtAuthGuard)
12 | async createOrder(@Body() request: CreateOrderRequest, @Req() req: any) {
13 | return this.ordersService.createOrder(request, req.cookies?.Authentication);
14 | }
15 |
16 | @Get()
17 | async getOrders() {
18 | return this.ordersService.getOrders();
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/apps/orders/src/orders.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { ConfigModule } from '@nestjs/config';
3 | import { MongooseModule } from '@nestjs/mongoose';
4 | import * as Joi from 'joi';
5 | import { DatabaseModule, RmqModule, AuthModule } from '@app/common';
6 | import { OrdersController } from './orders.controller';
7 | import { OrdersService } from './orders.service';
8 | import { OrdersRepository } from './orders.repository';
9 | import { Order, OrderSchema } from './schemas/order.schema';
10 | import { BILLING_SERVICE } from './constants/services';
11 |
12 | @Module({
13 | imports: [
14 | ConfigModule.forRoot({
15 | isGlobal: true,
16 | validationSchema: Joi.object({
17 | MONGODB_URI: Joi.string().required(),
18 | PORT: Joi.number().required(),
19 | }),
20 | envFilePath: './apps/orders/.env',
21 | }),
22 | DatabaseModule,
23 | MongooseModule.forFeature([{ name: Order.name, schema: OrderSchema }]),
24 | RmqModule.register({
25 | name: BILLING_SERVICE,
26 | }),
27 | AuthModule,
28 | ],
29 | controllers: [OrdersController],
30 | providers: [OrdersService, OrdersRepository],
31 | })
32 | export class OrdersModule {}
33 |
--------------------------------------------------------------------------------
/apps/orders/src/orders.repository.ts:
--------------------------------------------------------------------------------
1 | import { Injectable, Logger } from '@nestjs/common';
2 | import { AbstractRepository } from '@app/common';
3 | import { InjectModel, InjectConnection } from '@nestjs/mongoose';
4 | import { Model, Connection } from 'mongoose';
5 | import { Order } from './schemas/order.schema';
6 |
7 | @Injectable()
8 | export class OrdersRepository extends AbstractRepository {
9 | protected readonly logger = new Logger(OrdersRepository.name);
10 |
11 | constructor(
12 | @InjectModel(Order.name) orderModel: Model,
13 | @InjectConnection() connection: Connection,
14 | ) {
15 | super(orderModel, connection);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/apps/orders/src/orders.service.ts:
--------------------------------------------------------------------------------
1 | import { Inject, Injectable } from '@nestjs/common';
2 | import { ClientProxy } from '@nestjs/microservices';
3 | import { lastValueFrom } from 'rxjs';
4 | import { BILLING_SERVICE } from './constants/services';
5 | import { CreateOrderRequest } from './dto/create-order.request';
6 | import { OrdersRepository } from './orders.repository';
7 |
8 | @Injectable()
9 | export class OrdersService {
10 | constructor(
11 | private readonly ordersRepository: OrdersRepository,
12 | @Inject(BILLING_SERVICE) private billingClient: ClientProxy,
13 | ) {}
14 |
15 | async createOrder(request: CreateOrderRequest, authentication: string) {
16 | const session = await this.ordersRepository.startTransaction();
17 | try {
18 | const order = await this.ordersRepository.create(request, { session });
19 | await lastValueFrom(
20 | this.billingClient.emit('order_created', {
21 | request,
22 | Authentication: authentication,
23 | }),
24 | );
25 | await session.commitTransaction();
26 | return order;
27 | } catch (err) {
28 | await session.abortTransaction();
29 | throw err;
30 | }
31 | }
32 |
33 | async getOrders() {
34 | return this.ordersRepository.find({});
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/apps/orders/src/schemas/order.schema.ts:
--------------------------------------------------------------------------------
1 | import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
2 | import { AbstractDocument } from '@app/common';
3 |
4 | @Schema({ versionKey: false })
5 | export class Order extends AbstractDocument {
6 | @Prop()
7 | name: string;
8 |
9 | @Prop()
10 | price: number;
11 |
12 | @Prop()
13 | phoneNumber: string;
14 | }
15 |
16 | export const OrderSchema = SchemaFactory.createForClass(Order);
17 |
--------------------------------------------------------------------------------
/apps/orders/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 { OrdersModule } from './../src/orders.module';
5 |
6 | describe('OrdersController (e2e)', () => {
7 | let app: INestApplication;
8 |
9 | beforeEach(async () => {
10 | const moduleFixture: TestingModule = await Test.createTestingModule({
11 | imports: [OrdersModule],
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 |
--------------------------------------------------------------------------------
/apps/orders/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 |
--------------------------------------------------------------------------------
/apps/orders/tsconfig.app.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tsconfig.json",
3 | "compilerOptions": {
4 | "declaration": false,
5 | "outDir": "../../dist/apps/orders"
6 | },
7 | "include": ["src/**/*"],
8 | "exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
9 | }
10 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | services:
2 | orders:
3 | build:
4 | context: .
5 | dockerfile: ./apps/orders/Dockerfile
6 | target: development
7 | command: npm run start:dev orders
8 | env_file:
9 | - ./apps/orders/.env
10 | depends_on:
11 | - mongodb-primary
12 | - mongodb-secondary
13 | - mongodb-arbiter
14 | - billing
15 | - auth
16 | - rabbitmq
17 | volumes:
18 | - .:/usr/src/app
19 | - /usr/src/app/node_modules
20 | ports:
21 | - '3000:3000'
22 | billing:
23 | build:
24 | context: .
25 | dockerfile: ./apps/billing/Dockerfile
26 | target: development
27 | command: npm run start:dev billing
28 | env_file:
29 | - ./apps/billing/.env
30 | depends_on:
31 | - mongodb-primary
32 | - mongodb-secondary
33 | - mongodb-arbiter
34 | - rabbitmq
35 | - auth
36 | volumes:
37 | - .:/usr/src/app
38 | - /usr/src/app/node_modules
39 | auth:
40 | build:
41 | context: .
42 | dockerfile: ./apps/auth/Dockerfile
43 | target: development
44 | command: npm run start:dev auth
45 | ports:
46 | - '3001:3001'
47 | env_file:
48 | - ./apps/auth/.env
49 | depends_on:
50 | - mongodb-primary
51 | - mongodb-secondary
52 | - mongodb-arbiter
53 | - rabbitmq
54 | volumes:
55 | - .:/usr/src/app
56 | - /usr/src/app/node_modules
57 | rabbitmq:
58 | image: rabbitmq
59 | ports:
60 | - '5672:5672'
61 | mongodb-primary:
62 | image: docker.io/bitnami/mongodb:5.0
63 | environment:
64 | - MONGODB_ADVERTISED_HOSTNAME=mongodb-primary
65 | - MONGODB_REPLICA_SET_MODE=primary
66 | - MONGODB_ROOT_PASSWORD=password123
67 | - MONGODB_REPLICA_SET_KEY=replicasetkey123
68 | volumes:
69 | - 'mongodb_master_data:/bitnami/mongodb'
70 | ports:
71 | - '27017:27017'
72 |
73 | mongodb-secondary:
74 | image: docker.io/bitnami/mongodb:5.0
75 | depends_on:
76 | - mongodb-primary
77 | environment:
78 | - MONGODB_ADVERTISED_HOSTNAME=mongodb-secondary
79 | - MONGODB_REPLICA_SET_MODE=secondary
80 | - MONGODB_INITIAL_PRIMARY_HOST=mongodb-primary
81 | - MONGODB_INITIAL_PRIMARY_ROOT_PASSWORD=password123
82 | - MONGODB_REPLICA_SET_KEY=replicasetkey123
83 |
84 | mongodb-arbiter:
85 | image: docker.io/bitnami/mongodb:5.0
86 | depends_on:
87 | - mongodb-primary
88 | environment:
89 | - MONGODB_ADVERTISED_HOSTNAME=mongodb-arbiter
90 | - MONGODB_REPLICA_SET_MODE=arbiter
91 | - MONGODB_INITIAL_PRIMARY_HOST=mongodb-primary
92 | - MONGODB_INITIAL_PRIMARY_ROOT_PASSWORD=password123
93 | - MONGODB_REPLICA_SET_KEY=replicasetkey123
94 |
95 | volumes:
96 | mongodb_master_data:
97 | driver: local
98 |
--------------------------------------------------------------------------------
/libs/common/src/auth/auth.module.ts:
--------------------------------------------------------------------------------
1 | import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
2 | import * as cookieParser from 'cookie-parser';
3 | import { RmqModule } from '../rmq/rmq.module';
4 | import { AUTH_SERVICE } from './services';
5 |
6 | @Module({
7 | imports: [RmqModule.register({ name: AUTH_SERVICE })],
8 | exports: [RmqModule],
9 | })
10 | export class AuthModule implements NestModule {
11 | configure(consumer: MiddlewareConsumer) {
12 | consumer.apply(cookieParser()).forRoutes('*');
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/libs/common/src/auth/jwt-auth.guard.ts:
--------------------------------------------------------------------------------
1 | import {
2 | CanActivate,
3 | ExecutionContext,
4 | Inject,
5 | Injectable,
6 | UnauthorizedException,
7 | } from '@nestjs/common';
8 | import { ClientProxy } from '@nestjs/microservices';
9 | import { catchError, Observable, tap } from 'rxjs';
10 | import { AUTH_SERVICE } from './services';
11 |
12 | @Injectable()
13 | export class JwtAuthGuard implements CanActivate {
14 | constructor(@Inject(AUTH_SERVICE) private authClient: ClientProxy) {}
15 |
16 | canActivate(
17 | context: ExecutionContext,
18 | ): boolean | Promise | Observable {
19 | const authentication = this.getAuthentication(context);
20 | return this.authClient
21 | .send('validate_user', {
22 | Authentication: authentication,
23 | })
24 | .pipe(
25 | tap((res) => {
26 | this.addUser(res, context);
27 | }),
28 | catchError(() => {
29 | throw new UnauthorizedException();
30 | }),
31 | );
32 | }
33 |
34 | private getAuthentication(context: ExecutionContext) {
35 | let authentication: string;
36 | if (context.getType() === 'rpc') {
37 | authentication = context.switchToRpc().getData().Authentication;
38 | } else if (context.getType() === 'http') {
39 | authentication = context.switchToHttp().getRequest()
40 | .cookies?.Authentication;
41 | }
42 | if (!authentication) {
43 | throw new UnauthorizedException(
44 | 'No value was provided for Authentication',
45 | );
46 | }
47 | return authentication;
48 | }
49 |
50 | private addUser(user: any, context: ExecutionContext) {
51 | if (context.getType() === 'rpc') {
52 | context.switchToRpc().getData().user = user;
53 | } else if (context.getType() === 'http') {
54 | context.switchToHttp().getRequest().user = user;
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/libs/common/src/auth/services.ts:
--------------------------------------------------------------------------------
1 | export const AUTH_SERVICE = 'AUTH';
2 |
--------------------------------------------------------------------------------
/libs/common/src/database/abstract.repository.ts:
--------------------------------------------------------------------------------
1 | import { Logger, NotFoundException } from '@nestjs/common';
2 | import {
3 | FilterQuery,
4 | Model,
5 | Types,
6 | UpdateQuery,
7 | SaveOptions,
8 | Connection,
9 | } from 'mongoose';
10 | import { AbstractDocument } from './abstract.schema';
11 |
12 | export abstract class AbstractRepository {
13 | protected abstract readonly logger: Logger;
14 |
15 | constructor(
16 | protected readonly model: Model,
17 | private readonly connection: Connection,
18 | ) {}
19 |
20 | async create(
21 | document: Omit,
22 | options?: SaveOptions,
23 | ): Promise {
24 | const createdDocument = new this.model({
25 | ...document,
26 | _id: new Types.ObjectId(),
27 | });
28 | return (
29 | await createdDocument.save(options)
30 | ).toJSON() as unknown as TDocument;
31 | }
32 |
33 | async findOne(filterQuery: FilterQuery): Promise {
34 | const document = await this.model.findOne(filterQuery, {}, { lean: true });
35 |
36 | if (!document) {
37 | this.logger.warn('Document not found with filterQuery', filterQuery);
38 | throw new NotFoundException('Document not found.');
39 | }
40 |
41 | return document;
42 | }
43 |
44 | async findOneAndUpdate(
45 | filterQuery: FilterQuery,
46 | update: UpdateQuery,
47 | ) {
48 | const document = await this.model.findOneAndUpdate(filterQuery, update, {
49 | lean: true,
50 | new: true,
51 | });
52 |
53 | if (!document) {
54 | this.logger.warn(`Document not found with filterQuery:`, filterQuery);
55 | throw new NotFoundException('Document not found.');
56 | }
57 |
58 | return document;
59 | }
60 |
61 | async upsert(
62 | filterQuery: FilterQuery,
63 | document: Partial,
64 | ) {
65 | return this.model.findOneAndUpdate(filterQuery, document, {
66 | lean: true,
67 | upsert: true,
68 | new: true,
69 | });
70 | }
71 |
72 | async find(filterQuery: FilterQuery) {
73 | return this.model.find(filterQuery, {}, { lean: true });
74 | }
75 |
76 | async startTransaction() {
77 | const session = await this.connection.startSession();
78 | session.startTransaction();
79 | return session;
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/libs/common/src/database/abstract.schema.ts:
--------------------------------------------------------------------------------
1 | import { Prop, Schema } from '@nestjs/mongoose';
2 | import { SchemaTypes, Types } from 'mongoose';
3 |
4 | @Schema()
5 | export class AbstractDocument {
6 | @Prop({ type: SchemaTypes.ObjectId })
7 | _id: Types.ObjectId;
8 | }
9 |
--------------------------------------------------------------------------------
/libs/common/src/database/database.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { ConfigService } from '@nestjs/config';
3 | import { MongooseModule } from '@nestjs/mongoose';
4 |
5 | @Module({
6 | imports: [
7 | MongooseModule.forRootAsync({
8 | useFactory: (configService: ConfigService) => ({
9 | uri: configService.get('MONGODB_URI'),
10 | }),
11 | inject: [ConfigService],
12 | }),
13 | ],
14 | })
15 | export class DatabaseModule {}
16 |
--------------------------------------------------------------------------------
/libs/common/src/index.ts:
--------------------------------------------------------------------------------
1 | export * from './database/database.module';
2 | export * from './database/abstract.repository';
3 | export * from './database/abstract.schema';
4 | export * from './rmq/rmq.service';
5 | export * from './rmq/rmq.module';
6 | export * from './auth/auth.module';
7 | export * from './auth/jwt-auth.guard';
8 |
--------------------------------------------------------------------------------
/libs/common/src/rmq/rmq.module.ts:
--------------------------------------------------------------------------------
1 | import { DynamicModule, Module } from '@nestjs/common';
2 | import { ConfigService } from '@nestjs/config';
3 | import { ClientsModule, Transport } from '@nestjs/microservices';
4 | import { RmqService } from './rmq.service';
5 |
6 | interface RmqModuleOptions {
7 | name: string;
8 | }
9 |
10 | @Module({
11 | providers: [RmqService],
12 | exports: [RmqService],
13 | })
14 | export class RmqModule {
15 | static register({ name }: RmqModuleOptions): DynamicModule {
16 | return {
17 | module: RmqModule,
18 | imports: [
19 | ClientsModule.registerAsync([
20 | {
21 | name,
22 | useFactory: (configService: ConfigService) => ({
23 | transport: Transport.RMQ,
24 | options: {
25 | urls: [configService.get('RABBIT_MQ_URI')],
26 | queue: configService.get(`RABBIT_MQ_${name}_QUEUE`),
27 | },
28 | }),
29 | inject: [ConfigService],
30 | },
31 | ]),
32 | ],
33 | exports: [ClientsModule],
34 | };
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/libs/common/src/rmq/rmq.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@nestjs/common';
2 | import { ConfigService } from '@nestjs/config';
3 | import { RmqContext, RmqOptions, Transport } from '@nestjs/microservices';
4 |
5 | @Injectable()
6 | export class RmqService {
7 | constructor(private readonly configService: ConfigService) {}
8 |
9 | getOptions(queue: string, noAck = false): RmqOptions {
10 | return {
11 | transport: Transport.RMQ,
12 | options: {
13 | urls: [this.configService.get('RABBIT_MQ_URI')],
14 | queue: this.configService.get(`RABBIT_MQ_${queue}_QUEUE`),
15 | noAck,
16 | persistent: true,
17 | },
18 | };
19 | }
20 |
21 | ack(context: RmqContext) {
22 | const channel = context.getChannelRef();
23 | const originalMessage = context.getMessage();
24 | channel.ack(originalMessage);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/libs/common/tsconfig.lib.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tsconfig.json",
3 | "compilerOptions": {
4 | "declaration": true,
5 | "outDir": "../../dist/libs/common"
6 | },
7 | "include": ["src/**/*"],
8 | "exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
9 | }
10 |
--------------------------------------------------------------------------------
/nest-cli.json:
--------------------------------------------------------------------------------
1 | {
2 | "collection": "@nestjs/schematics",
3 | "sourceRoot": "apps/orders/src",
4 | "monorepo": true,
5 | "root": "apps/orders",
6 | "compilerOptions": {
7 | "webpack": true,
8 | "tsConfigPath": "apps/orders/tsconfig.app.json"
9 | },
10 | "projects": {
11 | "orders": {
12 | "type": "application",
13 | "root": "apps/orders",
14 | "entryFile": "main",
15 | "sourceRoot": "apps/orders/src",
16 | "compilerOptions": {
17 | "tsConfigPath": "apps/orders/tsconfig.app.json"
18 | }
19 | },
20 | "billing": {
21 | "type": "application",
22 | "root": "apps/billing",
23 | "entryFile": "main",
24 | "sourceRoot": "apps/billing/src",
25 | "compilerOptions": {
26 | "tsConfigPath": "apps/billing/tsconfig.app.json"
27 | }
28 | },
29 | "auth": {
30 | "type": "application",
31 | "root": "apps/auth",
32 | "entryFile": "main",
33 | "sourceRoot": "apps/auth/src",
34 | "compilerOptions": {
35 | "tsConfigPath": "apps/auth/tsconfig.app.json"
36 | }
37 | },
38 | "common": {
39 | "type": "library",
40 | "root": "libs/common",
41 | "entryFile": "index",
42 | "sourceRoot": "libs/common/src",
43 | "compilerOptions": {
44 | "tsConfigPath": "libs/common/tsconfig.lib.json"
45 | }
46 | }
47 | }
48 | }
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ordering-app",
3 | "version": "0.0.1",
4 | "description": "",
5 | "author": "",
6 | "private": true,
7 | "license": "UNLICENSED",
8 | "scripts": {
9 | "prebuild": "rimraf dist",
10 | "build": "nest build",
11 | "format": "prettier --write \"apps/**/*.ts\" \"libs/**/*.ts\"",
12 | "start": "nest start",
13 | "start:dev": "nest start --watch",
14 | "start:debug": "nest start --debug --watch",
15 | "start:prod": "node dist/main",
16 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
17 | "test": "jest",
18 | "test:watch": "jest --watch",
19 | "test:cov": "jest --coverage",
20 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
21 | "test:e2e": "jest --config ./apps/ordering-app/test/jest-e2e.json"
22 | },
23 | "dependencies": {
24 | "@nestjs/common": "^8.0.0",
25 | "@nestjs/config": "^2.0.0",
26 | "@nestjs/core": "^8.0.0",
27 | "@nestjs/jwt": "^8.0.1",
28 | "@nestjs/microservices": "^8.4.5",
29 | "@nestjs/mongoose": "^9.0.3",
30 | "@nestjs/passport": "^8.2.1",
31 | "@nestjs/platform-express": "^8.0.0",
32 | "amqp-connection-manager": "^4.1.3",
33 | "amqplib": "^0.9.0",
34 | "bcrypt": "^5.0.1",
35 | "class-transformer": "^0.5.1",
36 | "class-validator": "^0.13.2",
37 | "cookie-parser": "^1.4.6",
38 | "joi": "^17.6.0",
39 | "mongoose": "^6.3.3",
40 | "passport": "^0.5.2",
41 | "passport-jwt": "^4.0.0",
42 | "passport-local": "^1.0.0",
43 | "reflect-metadata": "^0.1.13",
44 | "rimraf": "^3.0.2",
45 | "rxjs": "^7.2.0"
46 | },
47 | "devDependencies": {
48 | "@nestjs/cli": "^8.0.0",
49 | "@nestjs/schematics": "^8.0.0",
50 | "@nestjs/testing": "^8.0.0",
51 | "@types/cookie-parser": "^1.4.3",
52 | "@types/express": "^4.17.13",
53 | "@types/jest": "27.0.2",
54 | "@types/node": "^16.0.0",
55 | "@types/passport-jwt": "^3.0.6",
56 | "@types/passport-local": "^1.0.34",
57 | "@types/supertest": "^2.0.11",
58 | "@typescript-eslint/eslint-plugin": "^5.0.0",
59 | "@typescript-eslint/parser": "^5.0.0",
60 | "eslint": "^8.0.1",
61 | "eslint-config-prettier": "^8.3.0",
62 | "eslint-plugin-prettier": "^4.0.0",
63 | "jest": "^27.2.5",
64 | "prettier": "^2.3.2",
65 | "source-map-support": "^0.5.20",
66 | "supertest": "^6.1.3",
67 | "ts-jest": "^27.0.3",
68 | "ts-loader": "^9.2.3",
69 | "ts-node": "^10.0.0",
70 | "tsconfig-paths": "^3.10.1",
71 | "typescript": "^4.3.5"
72 | },
73 | "jest": {
74 | "moduleFileExtensions": [
75 | "js",
76 | "json",
77 | "ts"
78 | ],
79 | "rootDir": ".",
80 | "testRegex": ".*\\.spec\\.ts$",
81 | "transform": {
82 | "^.+\\.(t|j)s$": "ts-jest"
83 | },
84 | "collectCoverageFrom": [
85 | "**/*.(t|j)s"
86 | ],
87 | "coverageDirectory": "./coverage",
88 | "testEnvironment": "node",
89 | "roots": [
90 | "/apps/",
91 | "/libs/"
92 | ],
93 | "moduleNameMapper": {
94 | "^@app/common(|/.*)$": "/libs/common/src/$1"
95 | }
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/tsconfig.build.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
4 | }
5 |
--------------------------------------------------------------------------------
/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": "es2017",
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 | "paths": {
21 | "@app/common": [
22 | "libs/common/src"
23 | ],
24 | "@app/common/*": [
25 | "libs/common/src/*"
26 | ]
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------