Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@nestjs-mod/prisma

nestjs-mod720MIT1.16.1TypeScript support: included

Next-generation Node.js and TypeScript ORM for NestJS-mod (preview version only for Postgres)

nestjs, nestjs-mod, modules, mod, prisma, prisma-js, database, core

readme

@nestjs-mod/prisma

Next-generation Node.js and TypeScript ORM for NestJS-mod (preview version only for Postgres)

NPM version monthly downloads Telegram Discord

Installation

npm i --save-dev prisma
npm i --save @prisma/client @nestjs-mod/prisma

Modules

Link Category Description
PrismaModule core Next-generation Node.js and TypeScript ORM for NestJS-mod (preview version only for Postgres)

Modules descriptions

PrismaModule

Next-generation Node.js and TypeScript ORM for NestJS-mod (preview version only for Postgres)

Use in NestJS

For add support prisma in NestJS please read https://docs.nestjs.com/recipes/prisma#set-up-prisma

Use with forRoot options.

import { InjectPrismaClient, PrismaModule } from '@nestjs-mod/prisma';
import { NestFactory } from '@nestjs/core';
import { randomUUID } from 'crypto';

import { Injectable, Module } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class AppService {
  constructor(
    @InjectPrismaClient()
    private readonly prismaService: PrismaClient
  ) {}

  async createUser({ externalUserId }: { externalUserId: string }) {
    return await this.prismaService.prismaUser.create({ data: { externalUserId } });
  }

  async getUsers() {
    return await this.prismaService.prismaUser.findMany();
  }
}

@Module({
  imports: [
    PrismaModule.forRoot({
      staticConfiguration: {
        prismaModule: import(`@prisma/prisma-user-client`),
        addMigrationScripts: true,
      },
    }),
  ],
  providers: [AppService],
})
export class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);

  const service = app.get<AppService>(AppService);
  const externalUserId = randomUUID();
  await service.createUser({ externalUserId });
  console.log(await service.getUsers()); // output: [{ externalUserId: '568a823e-65ea-46ba-aa57-0194ee67e0f9' }]
}

bootstrap();

An example of access to module services with forFeature.

import { InjectPrismaClient, PrismaModule } from '@nestjs-mod/prisma';
import { NestFactory } from '@nestjs/core';
import { randomUUID } from 'crypto';

import { Injectable, Module } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class FeatureService {
  constructor(
    @InjectPrismaClient()
    private readonly prismaService: PrismaClient
  ) {}

  async createUser({ externalUserId }: { externalUserId: string }) {
    return await this.prismaService.prismaUser.create({ data: { externalUserId } });
  }

  async getUsers() {
    return await this.prismaService.prismaUser.findMany();
  }
}
@Module({
  imports: [
    PrismaModule.forFeature({
      featureModuleName: 'FeatureModule',
    }),
  ],
  providers: [FeatureService],
})
export class FeatureModule {}

@Module({
  imports: [
    PrismaModule.forRoot({
      staticConfiguration: {
        prismaModule: import(`@prisma/prisma-user-client`),
        addMigrationScripts: true,
      },
    }),
    FeatureModule,
  ],
})
export class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);

  const service = app.get<FeatureService>(FeatureService);
  const externalUserId = randomUUID();
  await service.createUser({ externalUserId });
  console.log(await service.getUsers()); // output: [{ externalUserId: '568a823e-65ea-46ba-aa57-0194ee67e0f9' }]
}

bootstrap();

Use in NestJS-mod

An example of using forRoot with parameters, you can see the full example here https://github.com/nestjs-mod/nestjs-mod-contrib/tree/master/apps/example-prisma.

For Prisma to work, you must first connect the Docker Compose module and the Docker Compose module to work with the database.

import {
  DefaultNestApplicationInitializer,
  DefaultNestApplicationListener,
  InfrastructureMarkdownReportGenerator,
  PACKAGE_JSON_FILE,
  ProjectUtils,
  bootstrapNestApplication,
  isInfrastructureMode,
} from '@nestjs-mod/common';
import { DOCKER_COMPOSE_FILE, DockerCompose, DockerComposePostgreSQL } from '@nestjs-mod/docker-compose';
import { PRISMA_SCHEMA_FILE, PrismaModule } from '@nestjs-mod/prisma';
import { join } from 'path';
import { userFeatureName } from './app/app.constants';
import { AppModule } from './app/app.module';

const rootFolder = join(__dirname, '..', '..', '..');
const appFolder = join(rootFolder, 'apps', 'example-prisma');

bootstrapNestApplication({
  modules: {
    system: [
      ProjectUtils.forRoot({
        staticConfiguration: {
          applicationPackageJsonFile: join(appFolder, PACKAGE_JSON_FILE),
          packageJsonFile: join(rootFolder, PACKAGE_JSON_FILE),
          envFile: join(rootFolder, '.env'),
        },
      }),
      DefaultNestApplicationInitializer.forRoot(),
      DefaultNestApplicationListener.forRoot({
        staticConfiguration: {
          // When running in infrastructure mode, the backend server does not start.
          mode: isInfrastructureMode() ? 'silent' : 'listen',
        },
      }),
    ],
    core: [
      PrismaModule.forRoot({
        staticConfiguration: {
          schemaFile: join(appFolder, 'src', 'prisma', `${userFeatureName}-${PRISMA_SCHEMA_FILE}`),
          featureName: userFeatureName,
          prismaModule: isInfrastructureMode()
            ? import(`@nestjs-mod/prisma`)
            : // replace to your client after first run docs:infrastructure
              import(`@nestjs-mod/prisma`),
          addMigrationScripts: true,
        },
      }),
    ],
    feature: [AppModule.forRoot()],
    infrastructure: [
      InfrastructureMarkdownReportGenerator.forRoot({
        staticConfiguration: {
          markdownFile: join(appFolder, 'INFRASTRUCTURE.MD'),
          skipEmptySettings: true,
        },
      }),
      DockerCompose.forRoot({
        configuration: {
          dockerComposeFileVersion: '3',
          dockerComposeFile: join(appFolder, DOCKER_COMPOSE_FILE),
        },
      }),
      DockerComposePostgreSQL.forRoot(),
      DockerComposePostgreSQL.forFeature({
        featureModuleName: userFeatureName,
      }),
    ],
  },
});

After connecting the module to the application and npm run build and starting generation of documentation through npm run docs:infrastructure, you will have new files and scripts to run.

New scripts mostly package.json

{
  "scripts": {
    "_____prisma_____": "_____prisma_____",
    "prisma:migrate-dev-new:example-prisma": "./node_modules/.bin/nx run example-prisma:prisma-migrate-dev --create-only --name=new",
    "prisma:migrate-dev:example-prisma": "./node_modules/.bin/nx run example-prisma:prisma-migrate-dev --create-only",
    "prisma:migrate-deploy:example-prisma": "./node_modules/.bin/nx run example-prisma:prisma-migrate-deploy",
    "prisma:migrate-deploy": "./node_modules/.bin/nx run-many -t=prisma-migrate-deploy",
    "prisma:pull": "./node_modules/.bin/nx run-many -t=prisma-pull",
    "prisma:generate": "./node_modules/.bin/nx run-many -t=prisma-generate"
  },
  "scriptsComments": {
    "prisma:pull": ["Generating a prisma schema based on a database"],
    "prisma:generate": ["Generation of client prisma schema of all applications and modules"],
    "prisma:migrate-dev:example-prisma": [
      "Alias for create new migration for example-prisma (example: `npm run prisma:migrate-dev:example-prisma --name=new)`"
    ],
    "prisma:migrate-deploy": ["Applying migrations of all applications and modules"],
    "prisma:migrate-dev-new:example-prisma": ["Command to create new empty migration for example-prisma"],
    "prisma:migrate-deploy:example-prisma": ["Applying migrations for example-prisma"]
  }
}

Additional commands in the nx application project.json

{
  "targets": {
    "prisma-generate": {
      "executor": "nx:run-commands",
      "options": {
        "commands": [
          "./node_modules/.bin/prisma generate --schema=./apps/example-prisma/src/prisma/prisma-user-schema.prisma"
        ],
        "parallel": false,
        "envFile": "./.env",
        "color": true
      }
    },
    "prisma-pull": {
      "executor": "nx:run-commands",
      "options": {
        "commands": [
          "./node_modules/.bin/prisma db pull --schema=./apps/example-prisma/src/prisma/prisma-user-schema.prisma"
        ],
        "parallel": false,
        "envFile": "./.env",
        "color": true
      }
    },
    "prisma-migrate-dev": {
      "executor": "nx:run-commands",
      "options": {
        "commands": [
          "./node_modules/.bin/prisma migrate dev --schema=./apps/example-prisma/src/prisma/prisma-user-schema.prisma"
        ],
        "parallel": false,
        "envFile": "./.env",
        "color": true
      }
    },
    "prisma-migrate-deploy": {
      "executor": "nx:run-commands",
      "options": {
        "commands": [
          "./node_modules/.bin/prisma migrate deploy --schema=./apps/example-prisma/src/prisma/prisma-user-schema.prisma"
        ],
        "parallel": false,
        "envFile": "./.env",
        "color": true
      }
    }
  }
}

Example of a prisma schema schema.prisma

generator client {
  provider   = "prisma-client-js"
  engineType = "binary"
  output     = "../../../../node_modules/@prisma/prisma-user-client"
}

datasource db {
  provider          = "postgres"
  url               = env("PRISMA_PRISMA_USER_DATABASE_URL")
  shadowDatabaseUrl = env("PRISMA_PRISMA_USER_SHADOW_DATABASE_URL")
}

model PrismaUser {
  id             String   @id(map: "PK_PRISMA_USER") @default(dbgenerated("uuid_generate_v4()")) @db.Uuid
  externalUserId String   @unique(map: "UQ_PRISMA_USER") @db.Uuid
  createdAt      DateTime @default(now()) @db.Timestamp(6)
  updatedAt      DateTime @default(now()) @db.Timestamp(6)
}

New environment variable

PRISMA_ROOT_DATABASE_URL=postgres://postgres:postgres_password@localhost:5432/postgres?schema=public
PRISMA_PRISMA_USER_DATABASE_URL=postgres://prisma_user:prisma_user_password@localhost:5432/prisma_user?schema=public
PRISMA_PRISMA_USER_SHADOW_DATABASE_URL=postgres://prisma_user:prisma_user_password@localhost:5432/shadow_prisma_user?schema=public

For create all needs prisma clients, please run npm run generate.

When launched in the infrastructure documentation generation mode, the module creates an .env file with a list of all required variables, as well as an example example.env, where you can enter example variable values.

Shared providers

PrismaClientFactoryService, PrismaClient

Environments

Key Description Sources Constraints Default Value
databaseUrl Connection string for database with credentials (example: postgres://feat:feat_password@localhost:5432/feat?schema=public) obj['databaseUrl'], process.env['DATABASE_URL'] isNotEmpty (databaseUrl should not be empty) - -

Static configuration

Key Description Constraints Default Value
defaultLogger Default logger optional - -
prismaModule NodeJS module with Prisma modules optional - hidden
logging Logging types (all_queries or long_queries) optional long_queries -
maxQueryExecutionTime Max query execution time for detect long queries optional 5000 -
pingDatabaseIntervalMs Ping database interval (0 - disable) optional 0 -
featureName Prisma feature name for generate prefix to environments keys (infrastructure) optional - -
schemaFile Schema file for prisma (infrastructure) optional - -
addMigrationScripts The option specifies whether it is necessary to create scripts to work with database migrations, for those who use third-party applications to create and apply migrations in the database (infrastructure, example: https://flywaydb.org, https://www.npmjs.com/package/db-migrate) optional true -
customSchemaContent Unsafe string custom content for add to end of prisma schema file (infrastructure) optional - -
binaryTargets Binary targets (infrastructure) optional - -
engineType Binary engine type (binary and library) optional - -
output Directory where Prisma Client is generated, e.g. ../src/generated/prisma optional - -
provider Default provider optional prisma-client-js -
runtime Target runtime environment. Supported values: nodejs (alias node), deno, bun, deno-deploy, workerd (alias cloudflare), edge-light (alias vercel), react-native optional - -
moduleFormat Module format (esm or cjs). Determines whether import.meta.url or __dirname is used. optional - -
generatedFileExtension File extension for generated TypeScript files (ts, mts, cts). optional - -
importFileExtension File extension used in import statements. Can be ts, mts, cts, js, mjs, cjs, or empty (for bare imports). optional - -
previewFeatures Preview features (infrastructure) optional - -
nxProjectJsonFile Application or library project.json-file (nx) optional - -
prismaClientFactory PrismaClient factory function (example use for https://www.prisma.io/docs/orm/overview/databases/postgresql#using-the-node-postgres-driver) optional - -

Back to Top

License

MIT

changelog

1.16.0 (2025-06-05)

Features

  • add support new prisma options: runtime, moduleFormat, generatedFileExtension, importFileExtension and update prisma to 6.9.0 (093493a)

1.15.0 (2025-06-03)

Features

1.14.2 (2025-05-28)

Bug Fixes

  • add options for change main provider (73eddbf)

1.14.1 (2025-05-25)

Bug Fixes

  • update for small pach names (99055c9)

1.14.0 (2025-05-25)

Bug Fixes

  • update logic for create path to output (e3920d2)

Features

  • add "output" optios for change directory where Prisma Client is generated (89e6528)

1.13.0 (2025-05-24)

Features

  • add new feature module prisma-tools (1470204)

1.12.1 (2025-04-03)

Bug Fixes

  • add support use promise based function for prismaClientFactory (5c89a63)

1.12.0 (2025-04-02)

Features

1.11.4 (2025-02-20)

Bug Fixes

  • update pg-flyway version (91f058d)

1.11.3 (2025-01-27)

Bug Fixes

  • add options for change engineType (f849783)

1.11.2 (2025-01-24)

Bug Fixes

1.11.1 (2025-01-22)

Bug Fixes

  • lock version of case-anything (511d86b)

1.11.0 (2025-01-16)

Features

  • append new infrastructure module for work with pf-flyway (9a6ba03)

1.10.4 (2024-12-30)

Bug Fixes

1.10.3 (2024-12-30)

Bug Fixes

  • add previewFeatures to PrismaConfiguration (9264be6)

1.10.2 (2024-09-27)

Bug Fixes

  • add suport use empty featureName in prisma anf flyway modules (4f39089)

1.10.1 (2024-09-25)

Bug Fixes

  • reexprt FakePrismaClient as PrismaClient, for use as mock import prisma client in applications (84ce917)

1.10.0 (2024-09-22)

Bug Fixes

Features

  • add support use custom nxProjectJsonFile in prisma, docker-compose-postgresql, flyway (d8530d9)

1.9.2 (2024-08-15)

Bug Fixes

1.9.1 (2024-08-15)

Bug Fixes

  • added merging of the original application options with new options (4d126b8)
  • update nestjs-mod libs (3481d3a)

1.9.0 (2024-07-29)

Features

  • npm run nx -- migrate latest && npm run npx nx migrate --run-migrations (e16fb8a)
  • npm run update:lib-versions && npm run manual:prepare (4c27038)
  • npm run update:nestjs-mod-versions (f9ebf6b)

1.8.1 (2024-05-04)

Bug Fixes

1.8.0 (2024-03-07)

Features

  • update logic for search env keys in docker compose services, use service name as prefix for env key name (e544c7b)

1.7.0 (2024-03-06)

Features

  • add @nestjs-mod/authorizer for work with https://authorizer.dev/, add DockerComposeAuthorizer for deploy authorizer server, add option notStaticKeysOfEnvironments in docker services for exclude some keys from generated dot env file (12380a4)

1.6.9 (2024-03-04)

Bug Fixes

  • add binaryTargets to prisma configuration (0c8cac8)

1.6.8 (2024-03-04)

Bug Fixes

  • add binaryTargets to prisma configuration (9656b37)

1.6.7 (2024-03-04)

Bug Fixes

  • add check prisma schema name in commands before add new command (218b0f3)
  • removed all "--" as it caused a side effect and prevented the command from completing correctly (d5e3d36)

1.6.6 (2024-02-28)

Bug Fixes

  • add support correct order on write env key values (41f1e4b)

1.6.5 (2024-02-28)

Bug Fixes

  • add comment to env file about shadowDatabaseName (de5b69a)

1.6.4 (2024-02-27)

Bug Fixes

  • update getPrismaClientToken function for correct work (0292ea2)

1.6.3 (2024-02-25)

Bug Fixes

  • add ext methods to FakePrismaClient (c39adbf)
  • expose getServiceToken from docker modules, cache-modules, prisma and terminus (108dc60)

1.6.2 (2024-02-25)

Bug Fixes

  • add type TransactionPrismaClient (05b308c)

1.6.1 (2024-02-22)

Bug Fixes

  • add transform: new NumberTransformer() for all number options in settings (71fc6d8)

1.6.0 (2024-02-17)

Features

  • add support in prisma work with context mode (b3a1f55)

1.5.1 (2024-02-13)

Bug Fixes

  • add pingDatabaseIntervalMs to prisma config for disable setInterval (641b272)
  • rename all featureName options in modules (6d46c47)

1.5.0 (2024-02-13)

Features

  • add DockerComposeMinio in @nestjs-mod/docker-compose, add @nestjs-mod/minio (0d3f9b7)
  • add DockerComposeNginx to @nestjs-mod/docker-compose, add use nginx in docker-compose for minio and disable cors validations, update readme in all modules (87cb34a)

1.4.0 (2024-02-09)

Features

  • add GraphqlModule in @nestjs-mod/graphql, add @nestjs-mod/cache-manager, update code in @nestjs-mod/pino, update readme in all modules, update @nestjs-mod/common version (c36b138)

1.3.0 (2024-02-07)

Bug Fixes

Features

  • add DockerComposeRedis in @nestjs-mod/docker-compose, add @nestjs-mod/cache-manager, rename FlywayModule to Flyway, rename NestjsPinoLogger to NestjsPinoLoggerModule, rename TerminusHealthCheck to TerminusHealthCheckModule, remove all async work with fs (1c5474a)

1.2.2 (2024-02-01)

Bug Fixes

  • update package json file generator, remove add migrations script for prisma, when we disable addMigrationScripts options (8fea330)

1.2.1 (2024-02-01)

Bug Fixes

  • add create directory when we try create or update some files from infrastructure logic (90e3ea8)

1.2.0 (2024-02-01)

Bug Fixes

  • move dependencies from code to dependenciesInfo and readme, update generator for ecosystem.config.json (7aa6ce1)

Features

1.1.1 (2024-01-30)

Bug Fixes

  • update logic for generate package json scripts, add order for categories (66e0753)

1.1.0 (2024-01-30)

Features

  • the files and commands added to the infrastructure have been expanded, and examples of working with libraries have been added (7f6c852)

1.0.3 (2024-01-24)

Bug Fixes

1.0.2 (2024-01-24)

Bug Fixes

1.0.1 (2024-01-23)

Bug Fixes

  • add description of prisma mopdule to report and update sample with application, for correct generate report (46100d7)

1.0.0 (2024-01-23)

Bug Fixes

Features