PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, April 20, 2022

[FIXED] How to setup a multi-tenant connection in NestJS with Typeorm

 April 20, 2022     connection, multi-tenant, mysql, nestjs, typeorm     No comments   

Issue

I'm working on an application with a multi-tenant architecture (on MySQL) where we have a database with multiples schemas which are composed with some tables. Is there a way to create a simple connection with TypeOrm where I can connect to any available schema from my database? The documentation doesn't really talk about multi-tenancy so maybe it's impossible to do it with an easy approach?


Solution

Manage to got it working by creating a connection with the schema name on database option, then we can reuse this connection for later requests:

        const connectionName = `${db_schema_name}_connection`;
        try{
            return getConnection(connectionName);
        } catch(e){
            const options       = Object.assign({} , this.configService.get('DB_INFOS'));            
            options.name        = connectionName;
            options.database    = `yourdb_${db_schema_name}`;
        
            return await createConnection(options);
        }


Answered By - PedroSG
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing