Create a multi-tenancy application in Nest.js

Recap

In the first part, creating a Multi-tenancy application In Nest.js – Part 1, we set up the Nest.js framework and configured and tested the microservice architecture application using Nest.js. In its second part, we used Sequelize and Mongoose to access the database and tested for both MySQL database and MongoDB.

Asynchronous connection

In this part; we will see how to let the application connect to multiple databases depending on the request. Since it is a multi-tenancy application, each tenant has their own database containing their data that accesses the same application and the application must therefore connect to different databases. We will change the method and use of the pass repository forRootAsync() instead of forRoot(), we need a custom class for configuration.

For both Sequelize and Mongoose, add the following:

MongooseModule.forRootAsync({
    useClass:MongooseConfigService
  }),
SequelizeModule.forRootAsync({
      useClass:SequelizeConfigService
})

We will create a configuration file and two classes: MongooseConfigService and SequelizeConfigService

The plan here is to add injection for each incoming request and use a domain to switch between connections.

So we need @Injectable({scope:Scope.REQUEST}), and on the class constructor we use @Inject(REQUEST) private read-only request so that we can obtain host information from request data.

For example, let’s say the domain is example.com and we have a tenant named company1, then the domain will be company1.example.com. Same thing too company2 tenant, the domain will be company2.example.com and so on.

config / MongooseConfigService.ts

import { Inject, Injectable, Scope } from "@nestjs/common";
import { REQUEST } from "@nestjs/core";
import { MongooseModuleOptions, MongooseOptionsFactory } from "@nestjs/mongoose";

@Injectable({scope:Scope.REQUEST})
export class MongooseConfigService implements MongooseOptionsFactory {
    constructor(@Inject(REQUEST) private readonly request,){}

  createMongooseOptions(): MongooseModuleOptions {
    let domain:string[]
    let database="database_development"
    if(this.request.data ){
      domain=this.request.data['host'].split('.')
      console.log(this.request)
    }
    else{
      domain=this.request['headers']['host'].split('.')
    }

    console.log(domain)
    if(domain[0]!='127' && domain[0]!='www' && domain.length >2){
      database="tenant_"+domain[0]
      console.log('current DB',database)
    }
    return {
      uri: 'mongodb://localhost:27017/'+database,
    };
  }
}

config / SequelizeConfigService.ts

import { Inject, Injectable, Scope } from "@nestjs/common";
import { REQUEST } from "@nestjs/core";
import { CONTEXT, RedisContext, RequestContext } from "@nestjs/microservices";
import { SequelizeModuleOptions, SequelizeOptionsFactory} from "@nestjs/sequelize";

@Injectable({scope:Scope.REQUEST})
export class SequelizeConfigService implements SequelizeOptionsFactory {
    constructor(@Inject(REQUEST) private readonly request:RequestContext){}
    
    createSequelizeOptions(): SequelizeModuleOptions {

      let domain:string[]
      let database="database_development"
      if(this.request.data ){
        domain=this.request.data['host'].split('.')
        console.log(this.request)
      }
      else{
        domain=this.request['headers']['host'].split('.')
      }

      console.log(domain)
      if(domain[0]!='127' && domain[0]!='www' && domain.length >2){
        database="tenant_"+domain[0]
        console.log('current DB',database)
      }

    return {
      dialect: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'ismaeil',
      password: 'root',
      database: database,
      autoLoadModels: true,
      synchronize: true,
    };
  }
}

Testing

After completing the configuration, we need to do some work to test it because we need to map our local host and IP to a domain. I will try to use two ways to test the application locally, but for the production it will be a configuration in your domain provider.

1- Edit the host file on your local machine and edit this file each time you add a tenant

Go to the following file in Linux: /etc/hosts and in windows: c:windowssystem32driversetchosts and add

## lines
127.0.0.1    example.com
127.0.0.1    company1.example.com
127.0.0.1    company2.example.com

2- Use local DNS

In Linux, you can install Dnsmasq and follow these steps:

1- Install dnsmasq in NetworkManager.

2- Add the configuration file sudo nano /etc/NetworkManager/dnsmasq.d/dnsmasq-localhost.conf.

add this line to the file:

address=/.example.com/127.0.0.1

3- Restart the service sudo systemctl reload NetworkManager.

The source code is available in the Git branch multi-database.

That is all! In Part 4 we will add a security level and user roles.

.

Leave a Comment