A NestJS module that allows you use Prisma, set up multiple Prisma services, and use multi-tenancy in each Prisma service.

Overview

NestJS Prisma Module

Header

Tests Linting npm version

NPM

Installation

To use this package, first install it:

npm i @sabinthedev/nestjs-prisma

Basic Usage

In order to use this package, you will need one or more Prisma Clients set up in your project.

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PrismaClient } from '@prisma/client';
import { PrismaModule } from '@sabinthedev/nestjs-prisma';

@Module({
  imports: [
    PrismaModule.register({
      client: PrismaClient,
      name: 'PRISMA'
    })
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }

There are also various options you may pass to the register function to customize how Prisma Client is instantiated and how to handle connections and requests.

Multitenancy

This plugin allows you to handle multi-tenant applications by abstracting a service layer above Prisma Client to cache Prisma Client instances in-memory and select the appropriate tenant connection on each request.

Below is an example of how to configure PrismaModule to handle multiple tenants:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PrismaClient } from '@prisma/client';
import { PrismaModule } from '@sabinthedev/nestjs-prisma';

@Module({
  imports: [
    PrismaModule.register({
      client: PrismaClient,
      name: 'PRISMA',
      multitenancy: true,
      datasource: 'postgresql://johndoe:randompassword@localhost:5432/mydb'
    })
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }

When configuring multi-tenancy, the datasource key is required as it is used as the base URL on which the tenant database is added.

To access a specific tenant database, add a header to your HTTP request named x-tenant-id whose value is the name of the tenant DB you wish to access. PrismaModule will generate a new instance of Prisma Client using the base URL you provided along with the specification for the tenant database.

Example Request:

In the scenario below, your server is at localhost:3000 and has an endpoint /users. The client accessing the resource requesting data from a tenant database named tenant-name.

curl -XGET -H 'x-tenant-id: tenant-name' 'localhost:3000/users'

Supported Database Providers

Note: SQLite (or any database servers that do not support multiple databases) is not supported.

The list of supported database providers for this feature are as follows:

  • PostgreSQL
  • MySQL
  • SQL Server
  • MongoDB

More to be added soon...

API

register(options)

The register function registers PrismaModule and allows you to pass in options that change the behavior of the module and the generated Prisma Client instances. This function takes in a single parameter, options. This is an object with the following available keys:

Parameter Type Description
name string Required The dependency injection token to use with @Inject. See the docs for more info.
logging boolean Optional Enables logging within the module that gives insights how your connections are being handled.
client PrismaClient class or ClientConfig Required The PrismaClient class to be instantiated, or an object containing a reference to a PrismaClient class and a callback function that allows you to modify the instantiated class on a per-tenant basis.
options PrismaClient constructor args Optional See the Prisma Client API reference
multitenancy boolean Optional* A flag that turns on the multi-tenancy capabilities of this module.
datasource string Optional* A datasource URL that is used to manually override Prisma Client's datasource. This is used as the base URL when dynamically selecting tenant databases.

Note: If multitenancy OR datasources are present, both are required. The built-in type-safety will make this apparent.

ClientConfig

An object of the ClientConfig type is able to be provided instead of a PrismaClient class to the client option key. This object should contain:

Parameter Type Description
client PrismaClient Required A PrismaClient class
initializer Initializer Required A function that is called when a PrismaClient is instantiated.

initializer(client: PrismaClient, tenant: string) => PrismaClient

This function gives you access to the generated client and the associated tenant name (if any) so you can customize the client instance with functions such as $on, $use and more. The available client methods can be found here.

Within this function, you can provide any function you would like to run when a Prisma Client is instantiated.

The return of this function must be the Prisma Client.

Advanced Usage

In the scenario below, the module is configured to:

  • Use multi-tenancy
  • Log info on the connection handling
  • Initialize PrismaClient with logging enabled at the info level (see Prisma's docs on logging)
  • Hook into the $on('info') logging event to customize the message so it is more appropriate for a multi-tenant system
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PrismaClient } from '@prisma/client';
import { PrismaModule } from '@sabinthedev/nestjs-prisma';

@Module({
  imports: [
    PrismaModule.register({
      client: {
        class: PrismaMock,
        initializer: (client, tenant) => {
          client.$on('info', (e) => {
            console.log(`${tenant} INFO | ${e.message}`)
          })
          return client;
        },
      },
      logging: true,
      multitenancy: true,
      datasource: 'file:./dev.db',
      name: 'PRISMA',
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }

Multiple Prisma Modules

You may register this module multiple times within your application to provide access to different databases.

Configure a new Prisma schema. Make sure to specify a custom output in the client generator if your first client used the default location. This ensures the newly generated client does not override the one at node_modules/@prisma/client.

You can then register a second client in a way similar to the following:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PrismaModule } from '@sabinthedev/nestjs-prisma';

// Import your clients 
import { PrismaClient as AuthClient } from '../prisma-clients/auth';
import { PrismaClient as UsersClient } from '../prisma-clients/users';

@Module({
  imports: [
    // Register the module once for each client
    PrismaModule.register({
      client: AuthClient,
      name: 'AUTH',
    }),
    PrismaModule.register({
      client: UsersClient,
      name: 'USERS',
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }

In the above scenario, you may be working in a microservice architecture who's Authentication service uses a separate database than the Users service. The configuration above registers both clients as separate providers.

You, of course, have all of the granular control and options as before when registering multiple modules.

Author

I'm Sabin Adams!

sabinthedev

Contributors

None yet! But contributions are welcome!

License

Licensed under MIT.

Comments
Owner
Sabin Adams
I'm Sabin 👋 Developer Advocate @ Prisma | Full-Stack Web Developer and Content Creator
Sabin Adams
proxy 🦄 yxorp is your Web Proxy as a Service (SAAS) Multi-tenant, Multi-Threaded, with Cache & Article Spinner

proxy ?? yxorp is your Web Proxy as a Service (SAAS) Multi-tenant, Multi-Threaded, with Cache & Article Spinner. Batteries are included, Content Spinning and Caching Engine, all housed within a stunning web GUI. A unique high-performance, plug-and-play, multi-threaded website mirror and article spinner

4D/ҵ.com Dashboards 13 Dec 30, 2022
A product system made with NestJS. It's a service where you list products, create products or even delete them.

Products-API A product system made with NestJS. It's a service where you list products, create products or even delete them. What I used in this proje

Luiz Sanches 4 May 18, 2022
Calculates maximum composite SLA for a list of sequentially provided cloud services or your custom-defined services.

SlaMax Calculates maximum composite SLA for a list of sequentially provided cloud services or your custom-defined services. Here are a few use-cases y

Mikael Vesavuori 4 Sep 19, 2022
An npm package for demonstration purposes using TypeScript to build for both the ECMAScript Module format (i.e. ESM or ES Module) and CommonJS Module format. It can be used in Node.js and browser applications.

An npm package for demonstration purposes using TypeScript to build for both the ECMAScript Module format (i.e. ESM or ES Module) and CommonJS Module format. It can be used in Node.js and browser applications.

Snyk Labs 57 Dec 28, 2022
⚡ It is a simplified database module with multiple functions that you can use simultaneously with sqlite, yaml, firebase and json.

Prisma Database Developed with ?? by Roxza ⚡ An easy, open source database ?? Installation npm i prisma.db --save yarn add prisma.db ?? Importing impo

Roxza 21 Jan 3, 2023
Cindy Dorantes 12 Oct 18, 2022
Service Installer for VMware Tanzu is a one-click automation solution that enables VMware field engineers to easily and rapidly install, configure, and operate VMware Tanzu services across a variety of cloud infrastructures.

Service Installer for VMware Tanzu Service Installer for VMware Tanzu seeks to provide a one-click automation solution to enable our VMware engineers

VMware Tanzu 42 Dec 1, 2022
Experience Lab is a set of utilities that assist in creating instances of Microsoft Energy Data Services, performing data loads, and performing basic management operations.

Experience Lab - Microsoft Energy Data Services Build Status About Experience Lab is an automated, end-to-end deployment accelerator for Microsoft Ene

Microsoft 9 Dec 14, 2022
Borscht - A Russian service monitor to track the uptime of domains and services

borscht ?? Borscht is a simple uptime and status monitor of Russian sites and services You can view the public status page here ?? About ?? This proje

Grant Birkinbine 10 Jul 8, 2022
Mekna'7, a subsidiary of the ONCF group, which provides bus services to cities not served by train, needs to set up a computer system by creating a database for managing customer reservations.

Online-bus-ticket-reservation Introduction Hello everyone, this is a project that I have done for assignment. This project is a simple online bus tick

Hala Ziani 5 Oct 25, 2022
This repository aims to create a POC about authentication and authorization using NestJS, Prisma and JWT.

A progressive Node.js framework for building efficient and scalable server-side applications. Description Nest framework TypeScript starter repository

Vinícius Fraga Modesto 2 Nov 2, 2022
SET Revision is a website to help you identify "sets" in the card game SET.

Welcome to SET Revision! SET Revision is a website to help you identify "sets" in the card game SET. The code in this repository is aimed for learners

Benjamin Piper 2 Oct 3, 2022
Fullstack Turborepo starter. Typescript, Nestjs, Nextjs, Tailwind, Prisma, Github Actions, Docker, And Reverse proxy configured

Turborepo (NestJS + Prisma + NextJS + Tailwind + Typescript + Jest) Starter This is fullstack turborepo starter. It comes with the following features.

Ejaz Ahmed 132 Jan 9, 2023
A basic example of a GraphQL API built with NestJS, Prisma and TypeScript

A progressive Node.js framework for building efficient and scalable server-side applications. Description Nest framework TypeScript starter repository

Richard Hong 15 Dec 18, 2022
a simple wrapper nestjs dynamic module on top of surrealdb.js driver, with a consumer app to show case library in action, nothing fancy

README README Project Components Dynamic Module Consumer App Install SurrealDb Starts SurrealDb Init surrealDb Database Run App from Source Code Launc

Mário Monteiro 0 Oct 3, 2022
Functional Programming with NestJS, Prisma. immutable, pure, stateless

Functional-NestJS Functional Programming with NestJS, Prisma. immutable, pure, stateless. 1. Introduction A production ready typescript backend reposi

y0on2q 40 Dec 6, 2022
Application template for NestJS + Docker + Prisma + MySQL

nestjs-docker-prisma-mysql Application template for NestJS + Docker + Prisma + MySQL Setup # install $ yarn # Setup env file for database $ cp .env.e

fsubal 6 Oct 15, 2022
REST API for a rudimentary blog - from Prisma Day 22 NestJS workshop

NestJS Workshop Prisma Day 22 - Let's build a REST API with NestJS and Prisma! Welcome to the code repository for the Prisma Day 2022 NestJS Workshop!

Tasin Ishmam 13 Jan 3, 2023
This is a simple web application of a To-do List in which you can add, remove and edit all your tasks and also you can mark each task as completed and delete all completed ones.

To-Do List A simple web application of a to do list Built With HTML, CSS, JS, ES6 & Webpack Getting Started In this repository I created To-Do List SP

Juan Sebastian Sotomayor 12 Apr 11, 2022