├── .gitignore ├── .prettierrc ├── .vscode └── settings.json ├── Dockerfile ├── README.md ├── nest-cli.json ├── nodemon-debug.json ├── nodemon.json ├── package.json ├── src ├── app.module.ts ├── app.service.ts ├── auth │ ├── auth.constants.ts │ ├── auth.controller.spec.ts │ ├── auth.controller.ts │ ├── auth.dto.ts │ ├── auth.interfaces.ts │ ├── auth.module.ts │ ├── auth.service.spec.ts │ ├── auth.service.ts │ ├── token-requirements.decorator.ts │ ├── token.decorator.ts │ └── token.guard.ts ├── common │ └── entities │ │ └── pagination.entity.ts ├── file │ ├── file.controller.spec.ts │ ├── file.controller.ts │ ├── file.dto.ts │ ├── file.module.ts │ ├── file.service.spec.ts │ └── file.service.ts ├── main.ts ├── message │ ├── message.controller.spec.ts │ ├── message.controller.ts │ ├── message.dto.ts │ ├── message.gateway.ts │ ├── message.interface.ts │ ├── message.module.ts │ ├── message.service.spec.ts │ └── message.service.ts ├── redis-io.adapter.ts └── user │ ├── user.controller.spec.ts │ ├── user.controller.ts │ ├── user.interface.ts │ ├── user.module.ts │ ├── user.service.spec.ts │ └── user.service.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json ├── tsconfig.json ├── tslint.json └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .env -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": false, 3 | "singleQuote": true, 4 | "trailingComma": "es5" 5 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.autoSave": "onFocusChange", 3 | "editor.formatOnSave": true, 4 | "editor.tabSize": 2, 5 | "javascript.format.enable": false, 6 | } -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # base image 2 | FROM node:9.6.1 3 | 4 | # set working directory 5 | RUN mkdir /usr/src/app 6 | WORKDIR /usr/src/app 7 | 8 | # add `/usr/src/app/node_modules/.bin` to $PATH 9 | ENV PATH /usr/src/app/node_modules/.bin:$PATH 10 | 11 | # install and cache app dependencies 12 | COPY package.json ./package.json 13 | COPY yarn.lock ./yarn.lock 14 | RUN yarn 15 | 16 | # copy app 17 | COPY . . 18 | 19 | # start app 20 | CMD ["yarn", "start"] -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NestJS API Gateway 2 | 3 | ## What is this? 4 | A NestJS API Gateway recipe with JWT authentication, multi-node Web Sockets messaging, file upload and microservices TCP connections. 5 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "language": "ts", 3 | "collection": "@nestjs/schematics", 4 | "sourceRoot": "src" 5 | } 6 | -------------------------------------------------------------------------------- /nodemon-debug.json: -------------------------------------------------------------------------------- 1 | { 2 | "watch": ["src"], 3 | "ext": "ts", 4 | "ignore": ["src/**/*.spec.ts"], 5 | "exec": "node --inspect-brk -r ts-node/register -r tsconfig-paths/register src/main.ts" 6 | } 7 | -------------------------------------------------------------------------------- /nodemon.json: -------------------------------------------------------------------------------- 1 | { 2 | "watch": ["src"], 3 | "ext": "ts", 4 | "ignore": ["src/**/*.spec.ts"], 5 | "exec": "ts-node -r tsconfig-paths/register src/main.ts" 6 | } 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nestjs-api-gateway", 3 | "version": "0.0.0", 4 | "description": "NestJS API Gateway recipe with JWT authentication, multi-node Web Sockets messaging and microservice example", 5 | "author": "Sébastien Dan", 6 | "license": "MIT", 7 | "scripts": { 8 | "build": "tsc -p tsconfig.build.json", 9 | "format": "prettier --write \"src/**/*.ts\"", 10 | "start": "ts-node -r tsconfig-paths/register src/main.ts", 11 | "start:dev": "nodemon", 12 | "start:debug": "nodemon --config nodemon-debug.json", 13 | "prestart:prod": "rimraf dist && npm run build", 14 | "start:prod": "node dist/main.js", 15 | "lint": "tslint -p tsconfig.json -c tslint.json", 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": "^5.4.0", 24 | "@nestjs/core": "^5.4.0", 25 | "@nestjs/jwt": "^0.3.0", 26 | "@nestjs/microservices": "^5.7.2", 27 | "@nestjs/swagger": "^2.5.1", 28 | "@nestjs/websockets": "^5.7.2", 29 | "class-validator": "^0.9.1", 30 | "reflect-metadata": "^0.1.12", 31 | "rimraf": "^2.6.2", 32 | "rxjs": "^6.2.2", 33 | "socket.io-redis": "^5.2.0", 34 | "socketio-jwt": "^4.5.0", 35 | "typescript": "^3.0.1" 36 | }, 37 | "devDependencies": { 38 | "@nestjs/testing": "^5.1.0", 39 | "@types/dotenv": "^6.1.0", 40 | "@types/express": "^4.16.0", 41 | "@types/jest": "^23.3.1", 42 | "@types/multer": "^1.3.7", 43 | "@types/node": "^10.7.1", 44 | "@types/socket.io": "^2.1.2", 45 | "@types/socketio-jwt": "^0.0.0", 46 | "@types/supertest": "^2.0.5", 47 | "dotenv": "^6.2.0", 48 | "jest": "^23.5.0", 49 | "nodemon": "^1.18.3", 50 | "prettier": "^1.14.2", 51 | "supertest": "^3.1.0", 52 | "ts-jest": "^23.1.3", 53 | "ts-loader": "^4.4.2", 54 | "ts-node": "^7.0.1", 55 | "tsconfig-paths": "^3.5.0", 56 | "tslint": "5.11.0", 57 | "tslint-config-prettier": "^1.18.0", 58 | "tslint-config-standard": "^8.0.1" 59 | }, 60 | "jest": { 61 | "moduleFileExtensions": [ 62 | "js", 63 | "json", 64 | "ts" 65 | ], 66 | "rootDir": "src", 67 | "testRegex": ".spec.ts$", 68 | "transform": { 69 | "^.+\\.(t|j)s$": "ts-jest" 70 | }, 71 | "coverageDirectory": "../coverage", 72 | "testEnvironment": "node" 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common' 2 | 3 | import { AuthModule } from './auth/auth.module' 4 | import { MessageModule } from './message/message.module' 5 | import { UserModule } from './user/user.module' 6 | 7 | @Module({ 8 | imports: [AuthModule, MessageModule, UserModule], 9 | }) 10 | export class AppModule {} 11 | -------------------------------------------------------------------------------- /src/app.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | 3 | @Injectable() 4 | export class AppService { 5 | getHello(): string { 6 | return 'Hello World!'; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/auth/auth.constants.ts: -------------------------------------------------------------------------------- 1 | export const AuthConstants = { 2 | access_token: { 3 | options: { 4 | expiresIn: '30d', 5 | issuer: 'ISSUER_NAME', 6 | }, 7 | }, 8 | } 9 | -------------------------------------------------------------------------------- /src/auth/auth.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AuthController } from './auth.controller'; 3 | 4 | describe('Auth Controller', () => { 5 | let controller: AuthController; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | controllers: [AuthController], 10 | }).compile(); 11 | 12 | controller = module.get(AuthController); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(controller).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/auth/auth.controller.ts: -------------------------------------------------------------------------------- 1 | import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common' 2 | import { ApiBearerAuth, ApiOperation, ApiUseTags } from '@nestjs/swagger' 3 | 4 | import { CreateAuthUserDto, VerifyAuthUserByEmailDto } from './auth.dto' 5 | import { IAccessToken, IAuthUser, TokenTypeEnum } from './auth.interfaces' 6 | import { AuthService } from './auth.service' 7 | import { TokenRequirements } from './token-requirements.decorator' 8 | import { Token } from './token.decorator' 9 | import { TokenGuard } from './token.guard' 10 | 11 | @Controller('auth') 12 | @ApiUseTags('authentication') 13 | @UseGuards(TokenGuard) 14 | export class AuthController { 15 | constructor(private readonly authService: AuthService) {} 16 | 17 | @Get('getAuthUserByToken') 18 | @ApiOperation({ title: 'Verify token authenticity, sign in user if valid' }) 19 | @ApiBearerAuth() 20 | @TokenRequirements(TokenTypeEnum.CLIENT, []) 21 | public async getAuthUserByToken( 22 | @Token() token: IAccessToken 23 | ): Promise { 24 | const { exp, iat, iss, ...user } = token 25 | return this.authService.getAuthUser(user.id) 26 | } 27 | 28 | @Post('createAuthUser') 29 | @ApiOperation({ title: 'Sign up a new user' }) 30 | public async createAuthUser( 31 | @Body() createAuthUserDto: CreateAuthUserDto 32 | ): Promise<{ user: IAuthUser; token: string }> { 33 | const authUser = await this.authService.createAuthUser(createAuthUserDto) 34 | return { 35 | token: this.authService.createAccessTokenFromAuthUser(authUser), 36 | user: authUser, 37 | } 38 | } 39 | 40 | @Post('verifyAuthUserByEmail') 41 | @ApiOperation({ title: 'Sign in user via email and password' }) 42 | public async verifyAuthUserByEmail( 43 | @Body() verifyAuthUserByEmailDto: VerifyAuthUserByEmailDto 44 | ): Promise { 45 | const user = await this.authService.verifyAuthUserByEmail( 46 | verifyAuthUserByEmailDto 47 | ) 48 | return { user, token: this.authService.createAccessTokenFromAuthUser(user) } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/auth/auth.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiModelProperty } from '@nestjs/swagger' 2 | 3 | export class CreateAuthUserDto { 4 | @ApiModelProperty({ 5 | description: 'User email', 6 | example: 'test@test.com', 7 | required: true, 8 | type: 'string', 9 | }) 10 | public readonly email: string 11 | 12 | @ApiModelProperty({ 13 | description: 'User password', 14 | example: 'password', 15 | required: true, 16 | type: 'string', 17 | }) 18 | public readonly password: string 19 | } 20 | 21 | export class VerifyAuthUserByEmailDto { 22 | @ApiModelProperty({ 23 | description: 'User email', 24 | example: 'test@test.com', 25 | required: true, 26 | type: 'string', 27 | }) 28 | public readonly email: string 29 | 30 | @ApiModelProperty({ 31 | description: 'User password', 32 | example: 'password', 33 | required: true, 34 | type: 'string', 35 | }) 36 | public readonly password: string 37 | } 38 | -------------------------------------------------------------------------------- /src/auth/auth.interfaces.ts: -------------------------------------------------------------------------------- 1 | export interface IAuthUser { 2 | createdAt: Date 3 | email: string 4 | id: number 5 | role: UserRoleEnum 6 | updatedAt: Date 7 | } 8 | 9 | export interface IAccessToken { 10 | readonly email: string 11 | readonly exp: number 12 | readonly iat: number 13 | readonly id: number 14 | readonly iss: number 15 | readonly type: TokenTypeEnum 16 | } 17 | 18 | export enum TokenTypeEnum { 19 | CLIENT, 20 | SYSTEM, 21 | } 22 | 23 | export enum UserRoleEnum { 24 | REGULAR, 25 | } 26 | 27 | export const UserRoleEnumAsArray = Object.keys(UserRoleEnum) 28 | -------------------------------------------------------------------------------- /src/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common' 2 | import { AuthController } from './auth.controller' 3 | import { AuthService } from './auth.service' 4 | 5 | @Module({ 6 | controllers: [AuthController], 7 | providers: [AuthService], 8 | }) 9 | export class AuthModule {} 10 | -------------------------------------------------------------------------------- /src/auth/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 | -------------------------------------------------------------------------------- /src/auth/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpException, Injectable } from '@nestjs/common' 2 | import { Client, ClientProxy, Transport } from '@nestjs/microservices' 3 | import * as jwt from 'jsonwebtoken' 4 | 5 | import { AuthConstants } from './auth.constants' 6 | import { CreateAuthUserDto, VerifyAuthUserByEmailDto } from './auth.dto' 7 | import { IAccessToken, IAuthUser, TokenTypeEnum } from './auth.interfaces' 8 | 9 | @Injectable() 10 | export class AuthService { 11 | @Client({ 12 | options: { host: 'auth', port: 3000 }, 13 | transport: Transport.TCP, 14 | }) 15 | private client: ClientProxy 16 | 17 | public async getAuthUser(id: number): Promise { 18 | return this.client 19 | .send({ cmd: 'getAuthUser' }, id) 20 | .toPromise() 21 | .catch(error => { 22 | throw new HttpException(error, error.status) 23 | }) 24 | } 25 | 26 | public async createAuthUser( 27 | createAuthUserDto: CreateAuthUserDto 28 | ): Promise { 29 | return this.client 30 | .send({ cmd: 'createAuthUser' }, createAuthUserDto) 31 | .toPromise() 32 | .catch(error => { 33 | throw new HttpException(error, error.status) 34 | }) 35 | } 36 | 37 | public async verifyAuthUserByEmail( 38 | user: VerifyAuthUserByEmailDto 39 | ): Promise { 40 | return this.client 41 | .send({ cmd: 'verifyAuthUserByEmail' }, user) 42 | .toPromise() 43 | .catch(error => { 44 | throw new HttpException(error, error.status) 45 | }) 46 | } 47 | 48 | public validateAccessToken(token: string): IAccessToken { 49 | return jwt.verify(token, process.env.JWT_SECRET, { 50 | issuer: AuthConstants.access_token.options.issuer, 51 | }) as IAccessToken 52 | } 53 | 54 | public createAccessTokenFromAuthUser(user: IAuthUser): string { 55 | const payload = { 56 | email: user.email, 57 | id: user.id, 58 | roles: [user.role], 59 | type: TokenTypeEnum.CLIENT, 60 | } 61 | return jwt.sign( 62 | payload, 63 | process.env.JWT_SECRET, 64 | AuthConstants.access_token.options 65 | ) 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/auth/token-requirements.decorator.ts: -------------------------------------------------------------------------------- 1 | import { ReflectMetadata } from '@nestjs/common'; 2 | import { TokenTypeEnum, UserRoleEnum } from './auth.interfaces'; 3 | 4 | export const TokenRequirements = (requiredTokenType: TokenTypeEnum, requiredUserRoles: UserRoleEnum[]) => 5 | ReflectMetadata('tokenrequirements', new TokenRequirementsHelper(requiredTokenType, requiredUserRoles)); 6 | 7 | export class TokenRequirementsHelper { 8 | 9 | private requiredTokenType: TokenTypeEnum; 10 | private requiredUserRoles: UserRoleEnum[]; 11 | 12 | constructor(requiredTokenType: TokenTypeEnum, requiredUserRoles: UserRoleEnum[]) { 13 | this.requiredTokenType = requiredTokenType; 14 | this.requiredUserRoles = requiredUserRoles; 15 | } 16 | 17 | public tokenIsOfType(tokenType: TokenTypeEnum): boolean { 18 | return tokenType === this.requiredTokenType; 19 | } 20 | 21 | public tokenHasAllUserRoles(userRoles: UserRoleEnum[]): boolean { 22 | return this.requiredUserRoles.every(requiredRole => userRoles.indexOf(requiredRole) > -1) || this.requiredUserRoles.length === 0; 23 | } 24 | } -------------------------------------------------------------------------------- /src/auth/token.decorator.ts: -------------------------------------------------------------------------------- 1 | import { createParamDecorator } from '@nestjs/common' 2 | 3 | export const Token = createParamDecorator((_, req) => req.token) 4 | -------------------------------------------------------------------------------- /src/auth/token.guard.ts: -------------------------------------------------------------------------------- 1 | import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common' 2 | import { Reflector } from '@nestjs/core' 3 | 4 | import { AuthService } from './auth.service' 5 | import { TokenRequirementsHelper } from './token-requirements.decorator' 6 | 7 | @Injectable() 8 | export class TokenGuard implements CanActivate { 9 | constructor( 10 | private readonly reflector: Reflector, 11 | private readonly authService: AuthService 12 | ) {} 13 | 14 | public async canActivate(context: ExecutionContext) { 15 | // check if the decorator is present 16 | const tokenRequirements = this.reflector.get( 17 | 'tokenrequirements', 18 | context.getHandler() 19 | ) 20 | if (!tokenRequirements) { 21 | return true 22 | } else { 23 | const req = context.switchToHttp().getRequest() 24 | if ( 25 | req.headers.authorization && 26 | (req.headers.authorization as string).split(' ')[0] === 'Bearer' 27 | ) { 28 | try { 29 | // validate token 30 | const token = (req.headers.authorization as string).split(' ')[1] 31 | const decodedToken = await this.authService.validateAccessToken(token) 32 | 33 | // check if token is of the right type 34 | if (!tokenRequirements.tokenIsOfType(decodedToken.type)) return false 35 | 36 | // save token in request object 37 | req.token = decodedToken 38 | 39 | return true 40 | } catch (err) { 41 | return false 42 | } 43 | } else { 44 | return false 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/common/entities/pagination.entity.ts: -------------------------------------------------------------------------------- 1 | export interface IPagination { 2 | skip: number; 3 | take: number; 4 | } -------------------------------------------------------------------------------- /src/file/file.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing' 2 | import { FileController } from './file.controller' 3 | 4 | describe('File Controller', () => { 5 | let module: TestingModule 6 | beforeAll(async () => { 7 | module = await Test.createTestingModule({ 8 | controllers: [FileController], 9 | }).compile() 10 | }) 11 | it('should be defined', () => { 12 | const controller: FileController = module.get( 13 | FileController 14 | ) 15 | expect(controller).toBeDefined() 16 | }) 17 | }) 18 | -------------------------------------------------------------------------------- /src/file/file.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Body, 3 | Controller, 4 | FileInterceptor, 5 | Get, 6 | Post, 7 | UploadedFile, 8 | UseGuards, 9 | UseInterceptors, 10 | } from '@nestjs/common' 11 | import { 12 | ApiBearerAuth, 13 | ApiConsumes, 14 | ApiImplicitFile, 15 | ApiOperation, 16 | ApiUseTags, 17 | } from '@nestjs/swagger' 18 | 19 | import { IAccessToken, TokenTypeEnum } from '../auth/auth.interfaces' 20 | import { TokenRequirements } from '../auth/token-requirements.decorator' 21 | import { Token } from '../auth/token.decorator' 22 | import { TokenGuard } from '../auth/token.guard' 23 | import { FileMetadataDto } from './file.dto' 24 | import { FileService } from './file.service' 25 | 26 | @Controller('file') 27 | @ApiUseTags('file') 28 | @UseGuards(TokenGuard) 29 | export class FileController { 30 | constructor(private readonly fileService: FileService) {} 31 | 32 | @Post('upload') 33 | @ApiOperation({ title: 'Upload a file' }) 34 | @UseInterceptors(FileInterceptor('file')) 35 | @ApiConsumes('multipart/form-data') 36 | @ApiImplicitFile({ name: 'file', required: true, description: 'File' }) 37 | @ApiBearerAuth() 38 | @TokenRequirements(TokenTypeEnum.CLIENT, []) 39 | public async uploadFile( 40 | @UploadedFile() file: Express.Multer.File, 41 | @Body() meta: FileMetadataDto 42 | ) { 43 | return this.fileService.upload(file, meta) 44 | } 45 | 46 | @Post('download') 47 | @ApiOperation({ title: 'Download a file' }) 48 | @ApiBearerAuth() 49 | @TokenRequirements(TokenTypeEnum.CLIENT, []) 50 | public async downloadFile(@Body() meta: FileMetadataDto) { 51 | return this.fileService.download(meta) 52 | } 53 | 54 | @Get('avatar') 55 | @ApiOperation({ title: 'Download user avatar' }) 56 | @ApiBearerAuth() 57 | @TokenRequirements(TokenTypeEnum.CLIENT, []) 58 | public async downloadAvatar(@Token() token: IAccessToken) { 59 | const meta: FileMetadataDto = { 60 | container: 'avatar', 61 | name: `user-${token.id}`, 62 | } 63 | return this.fileService.download(meta) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/file/file.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiModelProperty } from '@nestjs/swagger' 2 | 3 | export class FileMetadataDto { 4 | @ApiModelProperty({ 5 | description: 'Container name', 6 | example: 'avatar', 7 | required: true, 8 | type: 'string', 9 | }) 10 | public readonly container: string 11 | 12 | @ApiModelProperty({ 13 | description: 'File name', 14 | example: 'user-3', 15 | required: true, 16 | type: 'string', 17 | }) 18 | public readonly name: string 19 | } 20 | -------------------------------------------------------------------------------- /src/file/file.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common' 2 | 3 | import { AuthModule } from '../auth/auth.module' 4 | import { AuthService } from '../auth/auth.service' 5 | import { FileController } from './file.controller' 6 | import { FileService } from './file.service' 7 | 8 | @Module({ 9 | controllers: [FileController], 10 | imports: [AuthModule], 11 | providers: [AuthService, FileService], 12 | }) 13 | export class FileModule {} 14 | -------------------------------------------------------------------------------- /src/file/file.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing' 2 | import { FileService } from './file.service' 3 | 4 | describe('FileService', () => { 5 | let service: FileService 6 | beforeAll(async () => { 7 | const module: TestingModule = await Test.createTestingModule({ 8 | providers: [FileService], 9 | }).compile() 10 | service = module.get(FileService) 11 | }) 12 | it('should be defined', () => { 13 | expect(service).toBeDefined() 14 | }) 15 | }) 16 | -------------------------------------------------------------------------------- /src/file/file.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpException, Injectable } from '@nestjs/common' 2 | import { Client, ClientProxy, Transport } from '@nestjs/microservices' 3 | 4 | import { FileMetadataDto } from './file.dto' 5 | 6 | @Injectable() 7 | export class FileService { 8 | @Client({ 9 | options: { host: 'file', port: 3000 }, 10 | transport: Transport.TCP, 11 | }) 12 | public client: ClientProxy 13 | 14 | public async upload( 15 | file: Express.Multer.File, 16 | meta: FileMetadataDto 17 | ): Promise { 18 | return this.client 19 | .send({ cmd: 'uploadFile' }, { file, meta }) 20 | .toPromise() 21 | .catch(error => { 22 | throw new HttpException(error, error.status) 23 | }) 24 | } 25 | 26 | public async download(meta: FileMetadataDto): Promise { 27 | return this.client 28 | .send({ cmd: 'downloadFile' }, meta) 29 | .toPromise() 30 | .catch(error => { 31 | throw new HttpException(error, error.status) 32 | }) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core' 2 | import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger' 3 | import * as dotenv from 'dotenv' 4 | 5 | import { AppModule } from './app.module' 6 | import { RedisIoAdapter } from './redis-io.adapter' 7 | 8 | async function bootstrap() { 9 | dotenv.config() 10 | const app = await NestFactory.create(AppModule) 11 | app.enableCors() // NOT FOR PRODUCTION 12 | app.useWebSocketAdapter(new RedisIoAdapter(app)) 13 | 14 | const options = new DocumentBuilder() 15 | .setTitle('NestJS API Gateway') 16 | .setDescription( 17 | 'Find here the list of endpoints to communicate with the microservices/APIs' 18 | ) 19 | .setVersion('1.0') 20 | .setSchemes('https') 21 | .addBearerAuth('Authorization') 22 | .build() 23 | 24 | const document = SwaggerModule.createDocument(app, options) 25 | SwaggerModule.setup('api/v1', app, document) 26 | 27 | await app.listen(3000) 28 | } 29 | bootstrap() 30 | -------------------------------------------------------------------------------- /src/message/message.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { MessageController } from './message.controller'; 3 | 4 | describe('Message Controller', () => { 5 | let module: TestingModule; 6 | beforeAll(async () => { 7 | module = await Test.createTestingModule({ 8 | controllers: [MessageController], 9 | }).compile(); 10 | }); 11 | it('should be defined', () => { 12 | const controller: MessageController = module.get(MessageController); 13 | expect(controller).toBeDefined(); 14 | }); 15 | }); 16 | -------------------------------------------------------------------------------- /src/message/message.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Body, 3 | Controller, 4 | Get, 5 | Param, 6 | Patch, 7 | Post, 8 | Query, 9 | UseGuards, 10 | } from '@nestjs/common' 11 | import { ApiBearerAuth, ApiUseTags } from '@nestjs/swagger' 12 | 13 | import { 14 | IAccessToken, 15 | TokenTypeEnum, 16 | UserRoleEnum, 17 | } from '../auth/auth.interfaces' 18 | import { AuthService } from '../auth/auth.service' 19 | import { TokenRequirements } from '../auth/token-requirements.decorator' 20 | import { Token } from '../auth/token.decorator' 21 | import { TokenGuard } from '../auth/token.guard' 22 | import { IPagination } from '../common/entities/pagination.entity' 23 | import { IUser } from '../user/user.interface' 24 | import { UserService } from '../user/user.service' 25 | import { 26 | CreateMessageDto, 27 | CreateThreadDto, 28 | FindParticipantInThreadDto, 29 | } from './message.dto' 30 | import { IParticipant, IThread } from './message.interface' 31 | import { MessageService } from './message.service' 32 | 33 | @Controller('message') 34 | @ApiUseTags('message') 35 | @UseGuards(TokenGuard) 36 | export class MessageController { 37 | constructor( 38 | private readonly authService: AuthService, 39 | private readonly messageService: MessageService, 40 | private readonly userService: UserService 41 | ) {} 42 | 43 | @Get('threads') 44 | @ApiBearerAuth() 45 | @TokenRequirements(TokenTypeEnum.CLIENT, []) 46 | public async findAllThreads(@Token() token: IAccessToken) { 47 | return this.messageService 48 | .findAllThreads(token.id) 49 | .then(async threads => 50 | Promise.all(threads.map(async x => this.getThreadMetaData(x, token.id))) 51 | ) 52 | } 53 | 54 | @Get('thread/:recipientUserId') 55 | @ApiBearerAuth() 56 | @TokenRequirements(TokenTypeEnum.CLIENT, []) 57 | public async findThreadFromParticipantsIds( 58 | @Token() token: IAccessToken, 59 | @Param('recipientUserId') recipientUserId: string 60 | ) { 61 | return this.messageService 62 | .findThreadFromParticipantsIds([token.id, +recipientUserId]) 63 | .then(async threadResult => { 64 | if (threadResult) { 65 | return this.getThreadMetaData(threadResult, token.id) 66 | } else { 67 | const newThread = { 68 | participants: [ 69 | { userId: token.id } as IParticipant, 70 | { userId: +recipientUserId } as IParticipant, 71 | ], 72 | } 73 | return this.getThreadMetaData(newThread as any, null, { 74 | teaser: true, 75 | }) 76 | } 77 | }) 78 | } 79 | 80 | @Post('thread') 81 | @ApiBearerAuth() 82 | @TokenRequirements(TokenTypeEnum.CLIENT, []) 83 | public async createThread( 84 | @Token() token: IAccessToken, 85 | @Body() createThreadDto: CreateThreadDto 86 | ) { 87 | const thread = await this.messageService.createThread(createThreadDto) 88 | 89 | const createMessageDto = { 90 | content: createThreadDto.firstMessageContent, 91 | threadId: thread.id, 92 | } as CreateMessageDto 93 | const findParticipantInThreadDto: FindParticipantInThreadDto = { 94 | threadId: thread.id, 95 | userId: token.id, 96 | } 97 | const participant = await this.messageService.findParticipantInThread( 98 | findParticipantInThreadDto 99 | ) 100 | createMessageDto.participantId = participant.id 101 | await this.messageService.createMessage(createMessageDto) 102 | 103 | return this.getThreadMetaData(thread, token.id) 104 | } 105 | 106 | @Get('messages/:threadId') 107 | @ApiBearerAuth() 108 | @TokenRequirements(TokenTypeEnum.CLIENT, []) 109 | public async findAllThreadMessages( 110 | @Param('threadId') threadId: string, 111 | @Query() query 112 | ) { 113 | const pagination: IPagination = { 114 | skip: query.skip || 0, 115 | take: query.take || 10, 116 | } 117 | return this.messageService.findAllThreadMessages(+threadId, pagination) 118 | } 119 | 120 | @Post('send') 121 | @ApiBearerAuth() 122 | @TokenRequirements(TokenTypeEnum.CLIENT, []) 123 | public async sendMessage( 124 | @Token() token: IAccessToken, 125 | @Body() createMessageDto: CreateMessageDto 126 | ) { 127 | const findParticipantInThreadDto: FindParticipantInThreadDto = { 128 | threadId: createMessageDto.threadId, 129 | userId: token.id, 130 | } 131 | const participant = await this.messageService.findParticipantInThread( 132 | findParticipantInThreadDto 133 | ) 134 | createMessageDto.participantId = participant.id 135 | 136 | const message = await this.messageService.createMessage(createMessageDto) 137 | 138 | return message 139 | } 140 | 141 | @Patch('unnew') 142 | @ApiBearerAuth() 143 | @TokenRequirements(TokenTypeEnum.CLIENT, []) 144 | public async unNewThreadMessages(@Body() data: { threadId: number }) { 145 | return this.messageService.unNewThreadMessages(data.threadId) 146 | } 147 | 148 | private async getThreadMetaData( 149 | thread: IThread, 150 | userId: number, 151 | options?: { teaser: boolean } 152 | ) { 153 | return { 154 | ...thread, 155 | latestMessage: thread.id 156 | ? await this.messageService.findLatestThreadMessage(thread.id) 157 | : '', 158 | newMessage: thread.id 159 | ? await this.messageService.checkIfThreadHasNewMessage( 160 | thread.id, 161 | userId 162 | ) 163 | : false, 164 | participants: await Promise.all( 165 | thread.participants.map(async y => { 166 | let user: IUser 167 | const authUser = await this.authService.getAuthUser(y.userId) 168 | 169 | switch (authUser.role) { 170 | case UserRoleEnum.REGULAR: 171 | user = await this.userService.getUserProfile(y.userId) 172 | break 173 | } 174 | 175 | user.id = y.id 176 | return user 177 | }) 178 | ), 179 | } 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /src/message/message.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiModelProperty } from '@nestjs/swagger' 2 | 3 | export class Participant { 4 | @ApiModelProperty({ 5 | description: 'User id', 6 | example: 1, 7 | required: true, 8 | type: 'number', 9 | }) 10 | public readonly userId: number 11 | } 12 | 13 | export class CreateThreadDto { 14 | @ApiModelProperty({ 15 | description: 'First message content', 16 | example: 'This is a message', 17 | required: true, 18 | type: 'string', 19 | }) 20 | public readonly firstMessageContent: string 21 | 22 | @ApiModelProperty({ 23 | description: 'Participants', 24 | isArray: true, 25 | maxLength: 2, 26 | minLength: 2, 27 | required: true, 28 | type: Participant, 29 | }) 30 | public readonly participants: Participant[] 31 | } 32 | 33 | export class CreateMessageDto { 34 | @ApiModelProperty({ 35 | description: 'Message content', 36 | example: 'This is a message', 37 | required: true, 38 | type: 'string', 39 | }) 40 | public readonly content: string 41 | 42 | public participantId: number 43 | 44 | @ApiModelProperty({ 45 | description: 'Thread id', 46 | example: 1, 47 | required: true, 48 | type: 'number', 49 | }) 50 | public readonly threadId: number 51 | } 52 | 53 | export class FindParticipantInThreadDto { 54 | @ApiModelProperty({ 55 | description: 'Thread id', 56 | example: 1, 57 | required: true, 58 | type: 'number', 59 | }) 60 | public readonly threadId: number 61 | 62 | @ApiModelProperty({ 63 | description: 'User id', 64 | example: 1, 65 | required: true, 66 | type: 'number', 67 | }) 68 | public readonly userId: number 69 | } 70 | 71 | export class FindOtherParticipantsInThreadDto { 72 | @ApiModelProperty({ 73 | description: 'Thread id', 74 | example: 1, 75 | required: true, 76 | type: 'number', 77 | }) 78 | public readonly threadId: number 79 | 80 | @ApiModelProperty({ 81 | description: 82 | 'Id of the user that should be excluded from the searched users', 83 | example: 1, 84 | required: true, 85 | type: 'number', 86 | }) 87 | public readonly userId: number 88 | } 89 | -------------------------------------------------------------------------------- /src/message/message.gateway.ts: -------------------------------------------------------------------------------- 1 | import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets' 2 | import { Socket } from 'socket.io' 3 | 4 | import { IMessage, IParticipant, IThread } from './message.interface' 5 | import { MessageService } from './message.service' 6 | 7 | @WebSocketGateway() 8 | export class MessageGateway { 9 | constructor(private readonly messageService: MessageService) {} 10 | 11 | @SubscribeMessage('SEND_MESSAGE_SUCCESS') 12 | public async sendMessage(io: Socket, data: IMessage): Promise { 13 | const participants: IParticipant[] = await this.messageService.findOtherParticipantsInThread( 14 | { threadId: data.thread.id, userId: (io as any).token.id } 15 | ) 16 | await this.dispatchMessage('SEND_MESSAGE_SUCCESS', io, participants, data) 17 | return data 18 | } 19 | 20 | @SubscribeMessage('CREATE_THREAD_SUCCESS') 21 | public async createThread(io: Socket, data: IThread): Promise { 22 | const participants: IParticipant[] = await this.messageService.findOtherParticipantsInThread( 23 | { threadId: data.id, userId: (io as any).token.id } 24 | ) 25 | await this.dispatchMessage('GET_THREAD_SUCCESS', io, participants, data) 26 | return data 27 | } 28 | 29 | // Using redis-io adapter custom hook/request to reach connected sockets on all nodes 30 | private async dispatchMessage( 31 | id: string, 32 | io: Socket, 33 | participants: IParticipant[], 34 | data: IMessage | IThread 35 | ) { 36 | for (const participant of participants) { 37 | ;(io.server.of('/').adapter as any).customRequest( 38 | participant.userId, 39 | (error: any, socketIds: any[]) => { 40 | if (error) { 41 | // tslint:disable-next-line:no-console 42 | console.log(error) 43 | } 44 | ;[].concat.apply([], socketIds).forEach(x => { 45 | io.to(x).emit(id, data) 46 | }) 47 | } 48 | ) 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/message/message.interface.ts: -------------------------------------------------------------------------------- 1 | export interface IThread { 2 | createdAt: Date 3 | id: number 4 | participants: IParticipant[] 5 | updatedAt: Date 6 | } 7 | 8 | export interface IMessage { 9 | content: string 10 | createdAt: Date 11 | id: number 12 | participant: IParticipant 13 | thread: IThread 14 | updatedAt: Date 15 | } 16 | 17 | export interface IParticipant { 18 | createdAt: Date 19 | id: number 20 | updatedAt: Date 21 | userId: number 22 | } 23 | -------------------------------------------------------------------------------- /src/message/message.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common' 2 | 3 | import { AuthModule } from '../auth/auth.module' 4 | import { AuthService } from '../auth/auth.service' 5 | import { UserService } from '../user/user.service' 6 | import { MessageController } from './message.controller' 7 | import { MessageGateway } from './message.gateway' 8 | import { MessageService } from './message.service' 9 | 10 | @Module({ 11 | controllers: [MessageController], 12 | imports: [AuthModule], 13 | providers: [AuthService, UserService, MessageGateway, MessageService], 14 | }) 15 | export class MessageModule {} 16 | -------------------------------------------------------------------------------- /src/message/message.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { MessageService } from './message.service'; 3 | 4 | describe('MessageService', () => { 5 | let service: MessageService; 6 | beforeAll(async () => { 7 | const module: TestingModule = await Test.createTestingModule({ 8 | providers: [MessageService], 9 | }).compile(); 10 | service = module.get(MessageService); 11 | }); 12 | it('should be defined', () => { 13 | expect(service).toBeDefined(); 14 | }); 15 | }); 16 | -------------------------------------------------------------------------------- /src/message/message.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpException, Injectable } from '@nestjs/common' 2 | import { Client, ClientProxy, Transport } from '@nestjs/microservices' 3 | 4 | import { IPagination } from '../common/entities/pagination.entity' 5 | import { 6 | CreateMessageDto, 7 | CreateThreadDto, 8 | FindOtherParticipantsInThreadDto, 9 | FindParticipantInThreadDto, 10 | } from './message.dto' 11 | import { IMessage, IParticipant, IThread } from './message.interface' 12 | 13 | @Injectable() 14 | export class MessageService { 15 | @Client({ 16 | options: { host: 'message', port: 3000 }, 17 | transport: Transport.TCP, 18 | }) 19 | private client: ClientProxy 20 | 21 | public async findAllThreads(userId: number): Promise { 22 | return this.client 23 | .send({ cmd: 'getAllThreads' }, userId) 24 | .toPromise() 25 | .catch(error => { 26 | throw new HttpException(error, error.status) 27 | }) 28 | } 29 | 30 | public async findThreadFromParticipantsIds(ids: number[]): Promise { 31 | return this.client 32 | .send({ cmd: 'getThreadFromParticipantsIds' }, ids) 33 | .toPromise() 34 | .catch(error => { 35 | throw new HttpException(error, error.status) 36 | }) 37 | } 38 | 39 | public async createThread( 40 | createThreadDto: CreateThreadDto 41 | ): Promise { 42 | return this.client 43 | .send({ cmd: 'createThread' }, createThreadDto) 44 | .toPromise() 45 | .catch(error => { 46 | throw new HttpException(error, error.status) 47 | }) 48 | } 49 | 50 | public async findAllThreadMessages( 51 | threadId: number, 52 | pagination: IPagination 53 | ): Promise { 54 | return this.client 55 | .send( 56 | { cmd: 'getAllThreadMessages' }, 57 | { threadId, pagination } 58 | ) 59 | .toPromise() 60 | .catch(error => { 61 | throw new HttpException(error, error.status) 62 | }) 63 | } 64 | 65 | public async findLatestThreadMessage(threadId: number): Promise { 66 | return this.client 67 | .send({ cmd: 'getLatestThreadMessage' }, threadId) 68 | .toPromise() 69 | .catch(error => { 70 | throw new HttpException(error, error.status) 71 | }) 72 | } 73 | 74 | public async checkIfThreadHasNewMessage( 75 | threadId: number, 76 | userId: number 77 | ): Promise { 78 | return this.client 79 | .send( 80 | { cmd: 'checkIfThreadHasNewMessage' }, 81 | { threadId, userId } 82 | ) 83 | .toPromise() 84 | .catch(error => { 85 | throw new HttpException(error, error.status) 86 | }) 87 | } 88 | 89 | public async findParticipantInThread( 90 | findParticipantInThreadDto: FindParticipantInThreadDto 91 | ): Promise { 92 | return this.client 93 | .send( 94 | { cmd: 'findParticipantInThread' }, 95 | findParticipantInThreadDto 96 | ) 97 | .toPromise() 98 | .catch(error => { 99 | throw new HttpException(error, error.status) 100 | }) 101 | } 102 | 103 | public async findOtherParticipantsInThread( 104 | findOtherParticipantsInThreadDto: FindOtherParticipantsInThreadDto 105 | ): Promise { 106 | return this.client 107 | .send( 108 | { cmd: 'findOtherParticipantsInThread' }, 109 | findOtherParticipantsInThreadDto 110 | ) 111 | .toPromise() 112 | .catch(error => { 113 | throw new HttpException(error, error.status) 114 | }) 115 | } 116 | 117 | public async createMessage( 118 | createMessageDto: CreateMessageDto 119 | ): Promise { 120 | return this.client 121 | .send({ cmd: 'createMessage' }, createMessageDto) 122 | .toPromise() 123 | .catch(error => { 124 | throw new HttpException(error, error.status) 125 | }) 126 | } 127 | 128 | public async unNewThreadMessages(threadId: number): Promise { 129 | return this.client 130 | .send({ cmd: 'unNewThreadMessages' }, threadId) 131 | .toPromise() 132 | .catch(error => { 133 | throw new HttpException(error, error.status) 134 | }) 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/redis-io.adapter.ts: -------------------------------------------------------------------------------- 1 | import { IoAdapter } from '@nestjs/websockets' 2 | import { Server, Socket } from 'socket.io' 3 | import * as redisIoAdapter from 'socket.io-redis' 4 | import * as socketioJwt from 'socketio-jwt' 5 | 6 | import { IAccessToken } from './auth/auth.interfaces' 7 | 8 | const redisAdapter = redisIoAdapter({ host: 'redis', port: 80 }) 9 | 10 | export class RedisIoAdapter extends IoAdapter { 11 | public createIOServer(port: number, options?: any): any { 12 | const server = super.createIOServer(port, options) 13 | server.adapter(redisAdapter) 14 | server.use( 15 | socketioJwt.authorize({ 16 | decodedPropertyName: 'token', 17 | handshake: true, 18 | secret: process.env.JWT_SECRET, 19 | }) 20 | ) 21 | 22 | server.of('/').adapter.customHook = ( 23 | userId: string, 24 | callback: (socketIds?: string[]) => void 25 | ) => { 26 | callback( 27 | Object.keys(server.sockets.connected) 28 | .map(key => server.sockets.connected[key]) 29 | .filter(x => x.token.id === userId) 30 | .map(x => x.id) 31 | ) 32 | } 33 | return server 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/user/user.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing' 2 | import { UserController } from './user.controller' 3 | 4 | describe('User Controller', () => { 5 | let module: TestingModule 6 | beforeAll(async () => { 7 | module = await Test.createTestingModule({ 8 | controllers: [UserController], 9 | }).compile() 10 | }) 11 | it('should be defined', () => { 12 | const controller: UserController = module.get( 13 | UserController 14 | ) 15 | expect(controller).toBeDefined() 16 | }) 17 | }) 18 | -------------------------------------------------------------------------------- /src/user/user.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, Param, UseGuards } from '@nestjs/common' 2 | import { ApiBearerAuth, ApiOperation, ApiUseTags } from '@nestjs/swagger' 3 | 4 | import { IAccessToken, TokenTypeEnum } from '../auth/auth.interfaces' 5 | import { TokenRequirements } from '../auth/token-requirements.decorator' 6 | import { Token } from '../auth/token.decorator' 7 | import { TokenGuard } from '../auth/token.guard' 8 | import { UserService } from './user.service' 9 | 10 | @Controller('user') 11 | @ApiUseTags('user') 12 | @UseGuards(TokenGuard) 13 | export class UserController { 14 | public constructor(private readonly userService: UserService) {} 15 | 16 | @Get('profile') 17 | @ApiOperation({ title: 'Get user profile' }) 18 | @ApiBearerAuth() 19 | @TokenRequirements(TokenTypeEnum.CLIENT, []) 20 | public async getUserProfile(@Token() token: IAccessToken) { 21 | return this.userService.getUserProfile(token.id) 22 | } 23 | 24 | @Get('profile/:userId') 25 | @ApiOperation({ title: 'Get user profile by user id' }) 26 | @ApiBearerAuth() 27 | @TokenRequirements(TokenTypeEnum.CLIENT, []) 28 | public async getUserProfileByUserId(@Param('userId') userId: number) { 29 | return this.userService.getUserProfile(userId) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/user/user.interface.ts: -------------------------------------------------------------------------------- 1 | export interface IUser { 2 | createdAt: Date 3 | firstName: string 4 | id: number 5 | lastName: string 6 | updatedAt: Date 7 | userId: number 8 | } 9 | -------------------------------------------------------------------------------- /src/user/user.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common' 2 | 3 | import { AuthModule } from '../auth/auth.module' 4 | import { AuthService } from '../auth/auth.service' 5 | import { UserController } from './user.controller' 6 | import { UserService } from './user.service' 7 | 8 | @Module({ 9 | controllers: [UserController], 10 | imports: [AuthModule], 11 | providers: [AuthService, UserService], 12 | }) 13 | export class UserModule {} 14 | -------------------------------------------------------------------------------- /src/user/user.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing' 2 | import { UserService } from './user.service' 3 | 4 | describe('UserService', () => { 5 | let service: UserService 6 | beforeAll(async () => { 7 | const module: TestingModule = await Test.createTestingModule({ 8 | providers: [UserService], 9 | }).compile() 10 | service = module.get(UserService) 11 | }) 12 | it('should be defined', () => { 13 | expect(service).toBeDefined() 14 | }) 15 | }) 16 | -------------------------------------------------------------------------------- /src/user/user.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpException, Injectable } from '@nestjs/common' 2 | import { Transport } from '@nestjs/common/enums/transport.enum' 3 | import { Client, ClientProxy } from '@nestjs/microservices' 4 | import { IUser } from './user.interface' 5 | 6 | @Injectable() 7 | export class UserService { 8 | @Client({ 9 | options: { host: 'user', port: 3000 }, 10 | transport: Transport.TCP, 11 | }) 12 | public client: ClientProxy 13 | 14 | public async getUserProfile(userId: number): Promise { 15 | return this.client 16 | .send({ cmd: 'getProfile' }, userId) 17 | .toPromise() 18 | .catch(error => { 19 | throw new HttpException(error, error.status) 20 | }) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import * as request from 'supertest'; 3 | import { AppModule } from './../src/app.module'; 4 | 5 | describe('AppController (e2e)', () => { 6 | let app; 7 | 8 | beforeEach(async () => { 9 | const moduleFixture: TestingModule = await Test.createTestingModule({ 10 | imports: [AppModule], 11 | }).compile(); 12 | 13 | app = moduleFixture.createNestApplication(); 14 | await app.init(); 15 | }); 16 | 17 | it('/ (GET)', () => { 18 | return request(app.getHttpServer()) 19 | .get('/') 20 | .expect(200) 21 | .expect('Hello World!'); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "**/*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 | "target": "es6", 9 | "sourceMap": true, 10 | "outDir": "./dist", 11 | "baseUrl": "./" 12 | }, 13 | "exclude": ["node_modules"] 14 | } 15 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "tslint:recommended", 4 | "tslint-config-standard", 5 | "tslint-config-prettier" 6 | ], 7 | "rules": { 8 | "jsx-no-lambda": false, 9 | "max-classes-per-file": false 10 | } 11 | } 12 | --------------------------------------------------------------------------------