├── .prettierrc ├── nest-cli.json ├── README.md ├── tsconfig.build.json ├── src ├── app.service.ts ├── tenant │ ├── tenant-service.decorator.ts │ ├── tenant.entity.ts │ └── tenant.module.ts ├── main.ts ├── books │ ├── book.entity.ts │ ├── books.controller.ts │ ├── books.module.ts │ └── books.service.ts ├── app.controller.ts ├── app.controller.spec.ts └── app.module.ts ├── test ├── jest-e2e.json └── app.e2e-spec.ts ├── tsconfig.json ├── .gitignore ├── .eslintrc.js └── package.json /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | A NestJS and TypeORM application that handles multi tenants with multi database 3 |

4 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /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/tenant/tenant-service.decorator.ts: -------------------------------------------------------------------------------- 1 | import { applyDecorators, Injectable, Scope } from '@nestjs/common'; 2 | 3 | export const TenantService = () => 4 | applyDecorators( 5 | Injectable({ scope: Scope.REQUEST }) 6 | ); 7 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | 4 | async function bootstrap() { 5 | const app = await NestFactory.create(AppModule); 6 | await app.listen(3000); 7 | } 8 | bootstrap(); 9 | -------------------------------------------------------------------------------- /src/books/book.entity.ts: -------------------------------------------------------------------------------- 1 | import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm'; 2 | 3 | @Entity() 4 | export class Book { 5 | 6 | @PrimaryGeneratedColumn() 7 | id: number; 8 | 9 | @Column() 10 | title: string; 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/tenant/tenant.entity.ts: -------------------------------------------------------------------------------- 1 | import { Column, Entity, PrimaryColumn, Unique } from 'typeorm'; 2 | 3 | @Entity() 4 | @Unique(['host']) 5 | export class Tenant { 6 | 7 | @PrimaryColumn() 8 | host: string; 9 | 10 | @Column() 11 | name: string; 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/app.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get } from '@nestjs/common'; 2 | import { AppService } from './app.service'; 3 | 4 | @Controller() 5 | export class AppController { 6 | constructor(private readonly appService: AppService) {} 7 | 8 | @Get() 9 | getHello(): string { 10 | return this.appService.getHello(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "target": "es2017", 9 | "sourceMap": true, 10 | "outDir": "./dist", 11 | "baseUrl": "./", 12 | "incremental": true 13 | }, 14 | "exclude": ["node_modules", "dist"] 15 | } 16 | -------------------------------------------------------------------------------- /src/books/books.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get } from '@nestjs/common'; 2 | import { BooksService } from './books.service'; 3 | import { Book } from './book.entity'; 4 | 5 | @Controller('books') 6 | export class BooksController { 7 | 8 | constructor(private readonly booksService: BooksService) {} 9 | 10 | @Get() 11 | async findAll(): Promise { 12 | return this.booksService.findAll(); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/books/books.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { BooksController } from './books.controller'; 3 | import { BooksService } from './books.service'; 4 | import { TenantModule } from '../tenant/tenant.module'; 5 | 6 | @Module({ 7 | imports: [ 8 | TenantModule, 9 | ], 10 | controllers: [ 11 | BooksController 12 | ], 13 | providers: [ 14 | BooksService 15 | ] 16 | }) 17 | export class BooksModule {} 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | yarn-debug.log* 10 | yarn-error.log* 11 | lerna-debug.log* 12 | 13 | # OS 14 | .DS_Store 15 | 16 | # Tests 17 | /coverage 18 | /.nyc_output 19 | 20 | # IDEs and editors 21 | /.idea 22 | .project 23 | .classpath 24 | .c9/ 25 | *.launch 26 | .settings/ 27 | *.sublime-workspace 28 | 29 | # IDE - VSCode 30 | .vscode/* 31 | !.vscode/settings.json 32 | !.vscode/tasks.json 33 | !.vscode/launch.json 34 | !.vscode/extensions.json -------------------------------------------------------------------------------- /src/books/books.service.ts: -------------------------------------------------------------------------------- 1 | import { Inject } from '@nestjs/common'; 2 | 3 | import { TenantService } from '../tenant/tenant-service.decorator'; 4 | import { TENANT_CONNECTION } from '../tenant/tenant.module'; 5 | import { Book } from './book.entity'; 6 | 7 | @TenantService() 8 | export class BooksService { 9 | 10 | constructor(@Inject(TENANT_CONNECTION) private connection) { } 11 | 12 | async findAll(): Promise { 13 | const repository = await this.connection.getRepository(Book); 14 | return repository.find(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /.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/eslint-recommended', 10 | 'plugin:@typescript-eslint/recommended', 11 | 'prettier', 12 | 'prettier/@typescript-eslint', 13 | ], 14 | root: true, 15 | env: { 16 | node: true, 17 | jest: true, 18 | }, 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': 'off', 22 | '@typescript-eslint/no-explicit-any': 'off', 23 | }, 24 | }; 25 | -------------------------------------------------------------------------------- /src/app.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | 5 | describe('AppController', () => { 6 | let appController: AppController; 7 | 8 | beforeEach(async () => { 9 | const app: TestingModule = await Test.createTestingModule({ 10 | controllers: [AppController], 11 | providers: [AppService], 12 | }).compile(); 13 | 14 | appController = app.get(AppController); 15 | }); 16 | 17 | describe('root', () => { 18 | it('should return "Hello World!"', () => { 19 | expect(appController.getHello()).toBe('Hello World!'); 20 | }); 21 | }); 22 | }); 23 | -------------------------------------------------------------------------------- /test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { INestApplication } from '@nestjs/common'; 3 | import * as request from 'supertest'; 4 | import { AppModule } from './../src/app.module'; 5 | 6 | describe('AppController (e2e)', () => { 7 | let app: INestApplication; 8 | 9 | beforeEach(async () => { 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ 11 | imports: [AppModule], 12 | }).compile(); 13 | 14 | app = moduleFixture.createNestApplication(); 15 | await app.init(); 16 | }); 17 | 18 | it('/ (GET)', () => { 19 | return request(app.getHttpServer()) 20 | .get('/') 21 | .expect(200) 22 | .expect('Hello World!'); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | 4 | import { AppController } from './app.controller'; 5 | import { AppService } from './app.service'; 6 | import { TenantModule } from './tenant/tenant.module'; 7 | import { Tenant } from './tenant/tenant.entity'; 8 | import { BooksModule } from './books/books.module'; 9 | 10 | @Module({ 11 | imports: [ 12 | TypeOrmModule.forRoot({ 13 | type: 'mysql', 14 | host: 'localhost', 15 | port: 3307, 16 | username: 'root', 17 | password: 'root', 18 | database: 'test', 19 | entities: [ Tenant ], 20 | synchronize: true, 21 | }), 22 | TenantModule, 23 | BooksModule, 24 | ], 25 | controllers: [AppController], 26 | providers: [AppService], 27 | }) 28 | export class AppModule {} 29 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "app-mulit-tenant", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": { 6 | "name": "Marco Esposito", 7 | "url": "https://github.com/marcoesposito" 8 | }, 9 | "private": true, 10 | "license": "UNLICENSED", 11 | "scripts": { 12 | "prebuild": "rimraf dist", 13 | "build": "nest build", 14 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 15 | "start": "nest start", 16 | "start:dev": "nest start --watch", 17 | "start:debug": "nest start --debug --watch", 18 | "start:prod": "node dist/main", 19 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 20 | "test": "jest", 21 | "test:watch": "jest --watch", 22 | "test:cov": "jest --coverage", 23 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 24 | "test:e2e": "jest --config ./test/jest-e2e.json" 25 | }, 26 | "dependencies": { 27 | "@nestjs/common": "^7.0.0", 28 | "@nestjs/core": "^7.0.0", 29 | "@nestjs/platform-express": "^7.0.0", 30 | "@nestjs/typeorm": "^7.1.0", 31 | "mysql": "^2.18.1", 32 | "reflect-metadata": "^0.1.13", 33 | "rimraf": "^3.0.2", 34 | "rxjs": "^6.5.4", 35 | "typeorm": "^0.2.25" 36 | }, 37 | "devDependencies": { 38 | "@nestjs/cli": "^7.0.0", 39 | "@nestjs/schematics": "^7.0.0", 40 | "@nestjs/testing": "^7.0.0", 41 | "@types/express": "^4.17.3", 42 | "@types/jest": "25.1.4", 43 | "@types/node": "^13.9.1", 44 | "@types/supertest": "^2.0.8", 45 | "@typescript-eslint/eslint-plugin": "^2.23.0", 46 | "@typescript-eslint/parser": "^2.23.0", 47 | "eslint": "^6.8.0", 48 | "eslint-config-prettier": "^6.10.0", 49 | "eslint-plugin-import": "^2.20.1", 50 | "jest": "^25.1.0", 51 | "prettier": "^1.19.1", 52 | "supertest": "^4.0.2", 53 | "ts-jest": "25.2.1", 54 | "ts-loader": "^6.2.1", 55 | "ts-node": "^8.6.2", 56 | "tsconfig-paths": "^3.9.0", 57 | "typescript": "^3.7.4" 58 | }, 59 | "jest": { 60 | "moduleFileExtensions": [ 61 | "js", 62 | "json", 63 | "ts" 64 | ], 65 | "rootDir": "src", 66 | "testRegex": ".spec.ts$", 67 | "transform": { 68 | "^.+\\.(t|j)s$": "ts-jest" 69 | }, 70 | "coverageDirectory": "../coverage", 71 | "testEnvironment": "node" 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/tenant/tenant.module.ts: -------------------------------------------------------------------------------- 1 | import { BadRequestException, MiddlewareConsumer, Module, Scope } from '@nestjs/common'; 2 | import { REQUEST } from '@nestjs/core'; 3 | import { TypeOrmModule } from '@nestjs/typeorm'; 4 | import { Connection, createConnection, getConnection } from 'typeorm'; 5 | 6 | import { Tenant } from './tenant.entity'; 7 | import { Book } from '../books/book.entity'; 8 | 9 | export const TENANT_CONNECTION = 'TENANT_CONNECTION'; 10 | 11 | @Module({ 12 | imports: [ 13 | TypeOrmModule.forFeature([Tenant]), 14 | ], 15 | providers: [ 16 | { 17 | provide: TENANT_CONNECTION, 18 | inject: [ 19 | REQUEST, 20 | Connection, 21 | ], 22 | scope: Scope.REQUEST, 23 | useFactory: async (request, connection) => { 24 | const tenant: Tenant = await connection.getRepository(Tenant).findOne(({ where: { host: request.headers.host } })); 25 | return getConnection(tenant.name); 26 | } 27 | } 28 | ], 29 | exports: [ 30 | TENANT_CONNECTION 31 | ] 32 | }) 33 | export class TenantModule { 34 | constructor(private readonly connection: Connection) { } 35 | 36 | configure(consumer: MiddlewareConsumer): void { 37 | consumer 38 | .apply(async (req, res, next) => { 39 | 40 | const tenant: Tenant = await this.connection.getRepository(Tenant).findOne(({ where: { host: req.headers.host } })); 41 | 42 | if (!tenant) { 43 | throw new BadRequestException( 44 | 'Database Connection Error', 45 | 'There is a Error with the Database!', 46 | ); 47 | } 48 | 49 | try { 50 | getConnection(tenant.name); 51 | next(); 52 | } catch (e) { 53 | 54 | const createdConnection: Connection = await createConnection({ 55 | name: tenant.name, 56 | type: "mysql", 57 | host: "localhost", 58 | port: 3307, 59 | username: 'root', 60 | password: 'root', 61 | database: tenant.name, 62 | entities: [ Book ], 63 | synchronize: true, 64 | }) 65 | 66 | if (createdConnection) { 67 | next(); 68 | } else { 69 | throw new BadRequestException( 70 | 'Database Connection Error', 71 | 'There is a Error with the Database!', 72 | ); 73 | } 74 | } 75 | }).forRoutes('*'); 76 | } 77 | } 78 | 79 | --------------------------------------------------------------------------------