Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

nestjs-prisma

Package Overview
Dependencies
Maintainers
1
Versions
63
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nestjs-prisma

Schematics to add Prisma support to a NestJS application

  • 0.13.0-dev.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
21K
decreased by-24.55%
Maintainers
1
Weekly downloads
 
Created
Source

NestJS Prisma Schematics

npm version Lib and Schematics CI

Add Prisma support to your NestJS application.

Installation

nest add nestjs-prisma

Example output

✔ Package installation in progress... ☕
Starting library setup...
? Do you like to generate your own PrismaService for customizations? No
? Do you like to Dockerize your application? Yes
? Which datasource provider do you want to use for `prisma init`? sqlite
    ✅️ Added prisma@2.26.0
    ✅️ Added @prisma/client@2.26.0
    ✅️ Added Prisma scripts [6]
    ✅️ Added Docker files
    ✅️ Add "prisma" directory to "excludes" in tsconfig.build.json
CREATE .dockerignore (42 bytes)
CREATE .env (192 bytes)
CREATE Dockerfile (455 bytes)
CREATE docker-compose.yml (474 bytes)
UPDATE package.json (2380 bytes)
UPDATE tsconfig.build.json (130 bytes)
✔ Packages installed successfully.
✔ Packages installed successfully.
    ✅️ Initialized Prisma - Datasource sqlite
  1. Use PrismaService and PrismaModule provided by nestjs-prisma

Answer the first question with no if you like to use the provided PrismaService and PrismaModule. Add PrismaModule to the imports section in your AppModule or other modules to gain access to PrismaService.

import { Module } from '@nestjs/common';
import { PrismaModule } from 'nestjs-prisma';

@Module({
  imports: [PrismaModule.forRoot()],
})
export class AppModule {}

PrismaModule allows to be used globally and to pass options to the PrismaClient.

import { Module } from '@nestjs/common';
import { PrismaModule } from 'nestjs-prisma';

@Module({
  imports: [
    PrismaModule.forRoot({
      isGlobal: true,
      prismaServiceOptions: {
        prismaOptions: { log: ['info'] },
        explicitConnect: true,
      },
    }),
  ],
})
export class AppModule {}

Additionally, PrismaModule provides a forRootAsync to pass options asynchronously. One option is to use a factory function:

import { Module } from '@nestjs/common';
import { PrismaModule } from 'nestjs-prisma';

@Module({
  imports: [
    PrismaModule.forRootAsync({
      isGlobal: true,
      useFactory: () => ({
        prismaOptions: {
          log: ['info', 'query'],
        },
        explicitConnect: false,
      }),
    }),
  ],
})
export class AppModule {}

You can inject dependencies such as ConfigModule to load options from .env files.

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { PrismaModule } from 'nestjs-prisma';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    PrismaModule.forRootAsync({
      isGlobal: true,
      useFactory: async (configService: ConfigService) => {
        return {
          prismaOptions: {
            log: [configService.get('log')],
            datasources: {
              db: {
                url: configService.get('DATABASE_URL'),
              },
            },
          },
          explicitConnect: configService.get('explicit'),
        };
      },
      inject: [ConfigService],
    }),
  ],
})
export class AppModule {}

Alternatively, you can use a class instead of a factory:

import { Module } from '@nestjs/common';
import { PrismaModule } from 'nestjs-prisma';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    PrismaModule.forRootAsync({
      isGlobal: true,
      useClass: PrismaConfigService,
    }),
  ],
})
export class AppModule {}

Create the PrismaConfigService and extend it with the PrismaOptionsFactory

import { Injectable } from '@nestjs/common';
import { PrismaOptionsFactory, PrismaServiceOptions } from '.nestjs-prisma';

@Injectable()
export class PrismaConfigService implements PrismaOptionsFactory {
  constructor() {
    // TODO inject any other service here like the `ConfigService`
  }

  createPrismaOptions(): PrismaServiceOptions | Promise<PrismaServiceOptions> {
    return {
      prismaOptions: {
        log: ['info', 'query'],
      },
      explicitConnect: true,
    };
  }
}
  1. Generate your own PrismaService and PrismaModule

Answer the first question with yes if you like to generate your own PrismaService and PrismaModule for further customizations. Add PrismaModule to the imports section in your AppModule or other modules to gain access to PrismaService.

import { Module } from '@nestjs/common';
import { PrismaModule } from './prisma/prisma.module';

@Module({
  imports: [PrismaModule],
})
export class AppModule {}

Note: It is safe to remove nestjs-prisma as dependency otherwise you have two import suggestions for PrismaService and PrismaModule.

PrismaClientExceptionFilter

nestjs-prisma provides an PrismaClientExceptionFilter to catch unhandled PrismaClientKnownRequestError and returning different status codes instead of 500 Internal server error.

To use the filter you have the following two options.

  1. Instantiate the filter in your main.ts and pass the HttpAdapterHost
//src/main.ts
import { ValidationPipe } from '@nestjs/common';
import { HttpAdapterHost, NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { PrismaClientExceptionFilter } from 'nestjs-prisma';

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

  const { httpAdapter } = app.get(HttpAdapterHost);
  app.useGlobalFilters(new PrismaClientExceptionFilter(httpAdapter));

  await app.listen(3000);
}
bootstrap();
  1. Use APP_FILTER token in any module
//src/app.module.ts
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { PrismaClientExceptionFilter } from 'nestjs-prisma';

@Module({
  providers: [
    {
      provide: APP_FILTER,
      useClass: PrismaClientExceptionFilter,
    },
  ],
})
export class AppModule {}

Additional options

All available flags:

Flag DescriptionType Default
 addPrismaServiceCreate a Prisma service extending the Prisma Client and module.booleanPrompted
 addDockerCreate a Dockerfile and docker-compose.yaml.booleanfalse
 dockerNodeImageVersionNode version for the builder and runner image.string14
 nameThe name for the Prisma service extending the Prisma Client and module.stringPrisma
 prismaVersionThe Prisma version to be installed.stringlatest
 skipInstallSkip installing dependency packages.booleanfalse
 skipPrismaInitSkip initializing Prisma.booleanfalse

You can pass additional flags to customize the schematic. For example, if you want to install a different version for Prisma use --prismaVersion flag:

nest add nestjs-prisma --prismaVersion 2.20.1

If you want to skip installing dependencies use --skipInstall flag:

nest add nestjs-prisma --skipInstall

Add Dockerfile and docker-compose.yaml, you can even use a different node version (14-alpine or 15).

Currently uses to PostgreSQL as a default database in docker-compose.yaml.

nest add nestjs-prisma --addDocker --dockerNodeImageVersion 14-alpine

Developing

Install @angular-devkit/schematics-cli to be able to use schematics command

npm i -g @angular-devkit/schematics-cli

Now build the schematics and run the schematic.

npm run build:schematics
# or
npm run dev:schematics

# dry-run
schematics .:nest-add

# execute schematics
schematics .:nest-add --debug false
# or
schematics .:nest-add --dry-run false

Helpful

Helpful article about Custom Angular Schematics which also applies to Nest.

Keywords

FAQs

Package last updated on 17 Aug 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc