Coder Social home page Coder Social logo

filipemacedo / multi-tenant-nestjs Goto Github PK

View Code? Open in Web Editor NEW

This project forked from pivee/multi-tenant-nestjs

0.0 0.0 0.0 118 KB

Starter kit for creating multi-tenant NestJS APIs using Prisma and PostgreSQL

JavaScript 5.48% TypeScript 94.52%

multi-tenant-nestjs's Introduction

Muti-tenant NestJS

This is a starter kit for creating multi-tenant NestJS APIs using Prisma and PostgreSQL.

How to run locally

1. Create ./.env file

MAIN_DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"
TENANT_DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"

Update the database URLs as required. If the database instances do not contain the right schema, you can create that using prisma db push once the dependencies are ready.

2. Install dependencies

pnpm install

Once the installation completes, postinstall should generate the PrismaClients.

3. Run dev or start

pnpm dev
pnpm start

How to update database schema

There are two .prisma files inside ./prisma/.

  • schema.prisma for the Main Database
  • tenant-schema.prisma for the Tenant Database

Do the necessary changes in the appropriate file and run the correct script.

Schema changes on the Main Database

pnpm prisma:main:push

Schema changes on the Tenant Database

pnpm prisma:tenant:push

How to use the PrismaClient inside NestJS Application

MainPrismaService

import { MainPrismaService } from '@/modules/prisma/main-prisma.service';

export class NestJSComponent {
  constructor(
    private readonly mainPrisma: MainPrismaService,
  ) {}
}
> Example:

@Get('/tenants')
async getTenants() {
  const tenants = await this.mainPrisma.tenant.findMany();

  return { tenants };
}

TenantPrismaService

import { TENANT_PRISMA_SERVICE, TenantPrismaService } from '@/modules/prisma/tenant-prisma.service';

export class NestJSComponent {
  constructor(
    @Inject(TENANT_PRISMA_SERVICE) private readonly tenantPrisma: TenantPrismaService
  ) {}
}
> Example:

@Get('/users')
async getUsers() {
  /**
   * Since we're using query extensions with the Prisma client,
   * this query should return only the users with the column
   * "tenantId" matching that in the request "x-tenant-code".
   */
  const users = await this.tenantPrisma.user.findMany();

  return { users };
}

Diagrams

Request-Response Life Cycle

flowchart TB
  Client((Client))
  API((API))
  MainDB[(MainDB)]
  Guards[[AuthGuard<br>UserGuard<br>RolesGuard]]

  Client --Request--> API --> RequestLoggerMiddleware --> TenantDatasourceMiddleware --> Guards --> Controller --> API --Response--> Client
  TenantDatasourceMiddleware---MainDB

Entity Relationship

erDiagram
    Main--Tenant {
        int id PK
        string code
        string name
        string website
        json metadata
        int datasourceId FK
    }
    Main--Datasource {
        int id PK
        string name
        string url
        json metadata
    }
    TenantDBX--Entity {
        int id PK
        any key
        int tenantId FK
    }
    Main--Tenant ||--o| Main--Datasource : has
    Main--Tenant ||--o{ TenantDBX--Entity : has

Data

Datasources

Datasource Main DB Tenant DB 1 Tenant DB 2 Tenant DB 3
Tenant(s) Metadata A
B
C
D
E
F
G
H
I

Data flow

flowchart LR
  API((API Main))
  APITSM[[TenantDatasourceMiddleware]]
  APIController[[Controller]]
  MainDb[(Main DB)]
  TenantDb1[(Tenant DB 1)]
  TenantDb2[(Tenant DB 2)]
  TenantDb3[(Tenant DB 3)]
  ClientA[Client A]
  ClientB[Client B]
  ClientC[Client C]
  ClientD[Client D]
  ClientE[Client E]
  ClientF[Client F]
  ClientG[Client G]
  ClientH[Client I]

  API <--(1)--> APITSM <--Get datasourceUrl--> MainDb
  API --(2)--> APIController
  ClientA --Data A--> API
  ClientB --Data B--> API
  ClientC --Data C--> API
  ClientD --Data D--> API
  ClientE --Data E--> API
  ClientF --Data F--> API
  ClientG --Data G--> API
  ClientH --Data H--> API
  ClientI --Data I--> API
  APIController -.Data A.->TenantDb1
  APIController -.Data B.->TenantDb1
  APIController -.Data C.->TenantDb1
  APIController -.Data D.->TenantDb2
  APIController -.Data E.->TenantDb2
  APIController -.Data F.->TenantDb2
  APIController -.Data G.->TenantDb3
  APIController -.Data H.->TenantDb3
  APIController -.Data I.->TenantDb3

multi-tenant-nestjs's People

Contributors

pivee avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.