Overview

Use Prisma ORM with NestJS lifecycle hooks. Includes health check and transaction helpers.

Features

  • Module lifecycle integration
  • Health check method
  • Transaction helper with retry
  • Connection management

Installation

npx hanma add prisma-service --framework nest

Dependencies

@prisma/client

Code

import {
  Injectable,
  OnModuleInit,
  OnModuleDestroy,
  Logger,
} from "@nestjs/common";
import { PrismaClient } from "@prisma/client";

@Injectable()
export class PrismaService
  extends PrismaClient
  implements OnModuleInit, OnModuleDestroy
{
  private readonly logger = new Logger(PrismaService.name);

  constructor() {
    super({
      log:
        process.env.NODE_ENV === "development"
          ? ["query", "info", "warn", "error"]
          : ["error"],
      errorFormat: "pretty",
    });
  }

  async onModuleInit() {
    try {
      await this.$connect();
      this.logger.log("Successfully connected to database");
    } catch (error) {
      this.logger.error("Failed to connect to database", error);
      throw error;
    }
  }

  async onModuleDestroy() {
    await this.$disconnect();
    this.logger.log("Disconnected from database");
  }

  async isHealthy(): Promise<boolean> {
    try {
      await this.$queryRaw`SELECT 1`;
      return true;
    } catch {
      return false;
    }
  }

  // Transaction helper with automatic retry
  async executeTransaction<T>(
    fn: (tx: Omit<PrismaClient, "$connect" | "$disconnect" | "$on" | "$transaction" | "$use" | "$extends">) => Promise<T>,
    maxRetries = 3
  ): Promise<T> {
    let retries = 0;

    while (retries < maxRetries) {
      try {
        return await this.$transaction(fn);
      } catch (error: any) {
        if (error.code === "P2034" && retries < maxRetries - 1) {
          retries++;
          this.logger.warn(`Transaction conflict, retrying (${retries}/${maxRetries})`);
          await new Promise((r) => setTimeout(r, 100 * retries));
          continue;
        }
        throw error;
      }
    }

    throw new Error("Transaction failed after max retries");
  }
}

Usage

constructor(private prisma: PrismaService) {}

const users = await this.prisma.user.findMany();

Dependencies

Frequently Asked Questions

How do I install Prisma Service?
Run the following command: npx hanma add prisma-service --framework nest
What dependencies are required?
This snippet requires: @prisma/client. Make sure to install them before using the snippet.
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to src/providers/prisma.service.ts.
Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.