NestJS Exporting: Establishing a connection for PostgreSQL multi tenancy

I have been working on implementing a multi tenancy architecture using postgres. The functionality is all in place within the tenant service, but now I need to import this connection into a different module called shops. Can anyone provide guidance on how to achieve this? The code you are currently looking at relates to the tenant module.

import { TenantService } from './tenant.service';
    import { TenantController } from './tenant.controller';

import { Global, Module, Scope } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Connection, createConnection, getConnectionManager } from 'typeorm';

import * as tenantsOrmconfig from '@config/typeorm/tenant-ormconfig';
import * as ormconfig from '@config/typeorm/ormconfig';
import { ShopModule } from './shop/shop.module';
import { AwsService } from '@config/aws';

const connectionFactory = {
  provide: 'CONNECTION',
  scope: Scope.REQUEST,
  useFactory: async (req) => {
    const teamId = req.headers['x-team-id'];
    console.log('xxxxxxxxxxxxxxxxxxx', teamId);

    if (teamId) {
      const connectionName = `${teamId}`;
      const connectionManager = getConnectionManager();

      if (connectionManager.has(connectionName)) {
        const connection = connectionManager.get(connectionName);
        return Promise.resolve(
          connection.isConnected ? connection : connection.connect(),
        );
      }

      return createConnection({
        ...tenantsOrmconfig,
        entities: [
          ...(tenantsOrmconfig as any).entities,
          ...(ormconfig as any).entities,
        ],
        name: connectionName,
        type: 'postgres',
        schema: connectionName,
      });
    }
  },
  inject: [REQUEST],
};

@Module({
  imports: [ShopModule],
  controllers: [TenantController],
  providers: [connectionFactory, TenantService],
  exports: ['CONNECTION'],
})
export class TenantModule {}

Below is an example of how the CONNECTION is utilized in the tenant service:

export class TenantService {
  gameRepository;
  constructor(@Inject('CONNECTION') connection) {
    this.gameRepository = connection.getRepository(TenantEntity);
   
  }

Answer №1

One way I tackled this issue was by utilizing the @Global() decorator, which allowed me to make the tenant module globally accessible throughout the entire project. When importing it into another module, I included:

imports: [forwardRef(() => TenantModule)],

This tenant module contains attributes for multi tenancy connection.

@Global()
@Module({
  imports: [ShopModule],
  controllers: [TenantController],
  providers: [connectionFactory, TenantService],
  exports: ['CONNECTION'],
})
export class TenantModule {}

In the shop module where schema selection is needed:

@Module({
  imports: [forwardRef(() => TenantModule)],
  controllers: [ShopController],
  providers: [ShopService, AwsService],
})
export class ShopModule {}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Removing spaces within brackets on dynamic properties for objects can be achieved by utilizing various methods such as

I've encountered an issue with my code that involves getting spaces within square brackets for the dynamic properties of an object. Even after searching through Code Style/Typescript/Spaces, I couldn't find any settings to adjust this. Could thes ...

Using the "+" operator to concatenate strings in a node.js application designed for querying movie data

I have a basic question regarding coding. I am relatively new to this field and still in the process of learning. I am currently working with a movie API using node. Since APIs require search terms without spaces, they need to be separated by a plus sign ...

What is the process for incorporating ejs into the source attribute of an image element?

Code Snippet: <img class="card-img-top" alt="..."><%= articles.image %><img> Server Setup: const express = require('express') const app = express() const router = require('./routes/article') app ...

Refresh the information being received without initiating a new process

I am fetching data from an ngrx/store I have subscribed to the data this.store.select(somedataList) .subscribe(myList => { myList.propertyA = "a different value"; }); After modifying the property values upon subscription, I must update the data ...

What is the process for choosing a specific id from a JSON structure?

Is there a way to extract specific data from a JSON format within an Ionic project? What is the process for selecting the ID associated with particular data in a JSON format? And how can I retrieve and display the value linked to the selected product&apos ...

Bringing in a script and invoking a function on a specific variable

As a newcomer to Typescript, I've been experimenting with some code I came across online to enhance the appearance of links on my website. <script src="https://wow.zamimg.com/widgets/power.js"></script> <script>var wowhead_tooltips ...

Troubleshooting problem with cookies in express-session

I've been working on an app with express.js and vue 3, incorporating session-based authentication. While everything functions perfectly locally, I've encountered issues when trying to deploy to production. Here's a snippet of the code where ...

How can you alter the background color of a Material UI select component when it is selected?

I am attempting to modify the background color of a select element from material ui when it is selected. To help illustrate, I have provided an image that displays how it looks when not selected and selected: Select Currently, there is a large gray backgr ...

Requesting for a template literal in TypeScript:

Having some trouble with my typescript code, it is giving me an error message regarding string concatenation, const content = senderDisplay + ', '+ moment(timestamp).format('YY/MM/DD')+' at ' + moment(timestamp).format(&apo ...

How can I run a TypeScript function within a JavaScript file?

I am working with a typescript file named file1.ts export function Hello(str: string) { console.log(str); } In addition, I have another file called index.js { require('./some.js'); } Furthermore, there is a script defined in the pack ...

Troubleshooting Problems with JSON Parsing in Node.js

After retrieving a JSON file and utilizing NodeJS to parse it, the structure of the JSON file appears as follows: { "id": 5, "x": 9.996, "y": 0.135, "v": { "x1": 0.653, "y1": -0.064 }, "z": 1.4730991609821347 }, { ...

Node can be used to minimize a static website

I have a website with static files like index.html, styles folder, scripts folder, and media folder. I want to create a script that minimizes all these files and organizes them in a dist folder while keeping the original structure. It seems like something ...

Extracting text from an HTML file and passing it to an Express.js server: A beginner

Currently, I'm attempting to retrieve the values from an HTML text field and store them in variables. I require HTML to capture these values and return the response within the .html file. HTML: <body> <form> ...

Creating an observer for a multiple selection dropdown in Aurelia: step by step tutorial

In my current setup, I have a dropdown menu that allows users to select a single option. This selection automatically provides me with the filtering value as an observable. Here is how it works: public months: any=[]; @observable public selectedMonth: ...

Installing npm on tiny core linux can be accomplished by following a few simple steps

After successfully installing Node.js using appbrowser-cli on my system, I noticed that npm was not installed. How can I go about installing npm on TinyCore Linux? I have attempted several solutions but none have been successful so far. ...

Leveraging an external TypeScript library in a TypeScript internal module

Imagine you find yourself in a situation where you need to utilize a typescript/node library within an internal module that is spanned across multiple .ts files. ApiRepositoryHelper.ts import * as requestPromise from "request-promise"; module ApiHelp ...

Error: npx is unable to locate the module named 'webpack'

I'm currently experimenting with a customized Webpack setup. I recently came across the suggestion to use npx webpack instead of node ./node_modules/webpack/bin/webpack.js. However, I am encountering some difficulties getting it to function as expecte ...

Is it considered safe to delete the npm-cache folder on a Windows system?

When running npm cache clean -f, I noticed that it was not able to fully clear the npm_cache folder located at C:\Users\jerry\AppData\Roaming\npm-cache. It only cleared some of the files within this directory. The command output d ...

Setting up of imagemagick node module using linuxbrew

Having trouble installing imagemagick-native as it's showing an error. Tried using the following command to install: npm install imagemaick-native --save > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c45414d ...

When integrating Axios with NextJS, ensure to include CORS headers to prevent any missing data

I have set up a NestJS backend with a NextJS frontend, both hosted separately. NestJS Backend To enable CORS in the backend, I included the following code: app.enableCors({ credentials: true, origin: process.env.FRONTEND_URL }); After checking the CORS ...