DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Importance of Transit Gateway in Anypoint Platform
  • How To Use JMS ActiveMQ With Mule 4 - Part 6
  • MuleSoft Anypoint Platform Complete Setup Guide
  • Application Retirement Using Informatica Data Archive

Trending

  • Building a Real-Time Audio Transcription System With OpenAI’s Realtime API
  • Analyzing Techniques to Provision Access via IDAM Models During Emergency and Disaster Response
  • How to Merge HTML Documents in Java
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques

Create a Multi-tenancy Application In Nest.js - Part 3

It's the 3rd part of our multi-tenancy application series and today we will see how to let the application connect to multiple databases depending on the request.

By 
Ismaeil Shajar user avatar
Ismaeil Shajar
·
Updated Dec. 25, 21 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
18.8K Views

Join the DZone community and get the full member experience.

Join For Free

Recap

In the first part, create a Multi-tenancy Application In Nest.js - Part 1, we set up the Nest.js framework and configured and tested the microservices 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.

Async 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 accessing the same application, thus the application needs to connect to different databases. We will change the pass repository option method and use forRootAsync() instead of forRoot(), we need to use 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 config 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 to use @Injectable({scope:Scope.REQUEST}), and on the class constructor, we use @Inject(REQUEST) private read-only request in order for us to get host information from request data.

For example, let say the domain is example.com, and we have a tenant called company1, then the domain will be company1.example.com. The same thing for 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,
    };
  }
}


Performance - Production

In production, we need to avoid creating connections in every request so we will do some edits in the user module and services.

Solution

Our problem here is connection was created for every request and this connection is not close and also I don't reuse it. So we can use an even close connection or use the existing connection in a new request or use both and manage when creating and when close.

Closing Connection

To close the connection first we need to access it. by naming connections we can access the connection using @InjectConnection then in service, we can close the connection every time after finishing. So we need these edits in:

user-service.module.ts


     SequelizeModule.forRootAsync({
      name: 'development',
       useClass:SequelizeConfigService
     }),
     SequelizeModule.forFeature([Users], 'development')], // use connection name in forFeature


And in:

user-service.service.ts

export class UserServiceService {
  constructor(
    @InjectConnection('development') private readonly sequelize: Sequelize, // access connection by name 'development'
    @InjectModel(Users, 'development')
  private readonly userModel: typeof Users){}
  async findAll() {
    let result =await this.userModel.findAll()
    this.sequelize.close() // after  every use will close connection
    return result;
  }
  /// the rest 
}


Use Existing Connection

In order to prevent the creation of SequelizeConfigService inside SequelizeModule and use a provider imported from a different module, you can use the `useExisting` syntax.

Additionally, we need to create an external module that provides sequelize configuration.

Create a new file named user-config.module.ts


@Module({
  providers: [SequelizeConfigService],
  exports:[SequelizeConfigService]
})

export class UserConfigModule {}


Then edit user-service.module.ts

SequelizeModule.forRootAsync({
    imports:[UserConfigModule],
    useExisting: SequelizeConfigService,
  }),

Use Both

if we add the ability to use both ways, code will be like this:

user-service.module.ts

@Module({
   imports: [
  SequelizeModule.forRootAsync({
    imports:[UserConfigModule],
    name: 'development',
    useExisting: SequelizeConfigService,
  }),
    SequelizeModule.forFeature([Users], 'development')],
  controllers: [UserServiceController],
  providers: [UserServiceService],
})

export class UserServiceModule {}


user-service.service.ts

@Injectable()
export class UserServiceService {
  constructor(@InjectConnection('development') private readonly sequelize: Sequelize,
    @InjectModel(Users, 'development')
  private readonly userModel: typeof Users){}
  async findAll() {
    let result =await this.userModel.findAll()
    //console.log(this.sequelize.close())  // optional or you can manage it 
    return result;
  }
  
  async create( createUserDto:CreateUserDto):Promise<Users> {
    return this.userModel.create(<Users>createUserDto)
    
  }
}


And we have a new module:

user-config.module.ts

import { Module } from '@nestjs/common';
import { SequelizeConfigService } from './sequelize-config-service';

@Module({
  providers: [SequelizeConfigService],
  exports:[SequelizeConfigService]
})

export class UserConfigModule {}


Testing

After finishing the configuration, we need to do some work to test it because we need to map our localhost 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 Hosts File in Your Local Machine and Edit This File Every Time You Add a Tenant

Go to the following file in Linux: /etc/hosts and in windows c:\windows\system32\drivers\etc\hosts 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 in 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's all! In part 4, we are going to add a security level and user roles.

application Connection (dance)

Opinions expressed by DZone contributors are their own.

Related

  • Importance of Transit Gateway in Anypoint Platform
  • How To Use JMS ActiveMQ With Mule 4 - Part 6
  • MuleSoft Anypoint Platform Complete Setup Guide
  • Application Retirement Using Informatica Data Archive

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!