0
0
NestJSframework~5 mins

Prisma Client usage in NestJS

Choose your learning style9 modes available
Introduction

Prisma Client helps you talk to your database easily. It lets you get, add, change, or delete data without writing complex SQL.

When you want to read data from your database in a NestJS app.
When you need to add new records to your database safely.
When you want to update or delete data based on user actions.
When you want to avoid writing raw SQL queries and use simple JavaScript instead.
Syntax
NestJS
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

// Example: Get all users
async function main() {
  const users = await prisma.user.findMany();
  console.log(users);
}

main();

PrismaClient is imported from '@prisma/client' and instantiated once.

Use async/await to handle database calls because they return promises.

Examples
Fetches all users from the 'user' table.
NestJS
const allUsers = await prisma.user.findMany();
Adds a new user with name and email.
NestJS
const newUser = await prisma.user.create({ data: { name: 'Anna', email: 'anna@example.com' } });
Changes the name of the user with id 1.
NestJS
const updatedUser = await prisma.user.update({ where: { id: 1 }, data: { name: 'Anna Smith' } });
Removes the user with id 1 from the database.
NestJS
const deletedUser = await prisma.user.delete({ where: { id: 1 } });
Sample Program

This NestJS service uses Prisma Client to connect to the database, add a user, and fetch all users. It connects when the module starts and disconnects when it stops.

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

@Injectable()
export class UserService implements OnModuleInit, OnModuleDestroy {
  private prisma = new PrismaClient();

  async onModuleInit() {
    await this.prisma.$connect();
  }

  async onModuleDestroy() {
    await this.prisma.$disconnect();
  }

  async getAllUsers() {
    return await this.prisma.user.findMany();
  }

  async createUser(name: string, email: string) {
    return await this.prisma.user.create({
      data: { name, email },
    });
  }
}

// Example usage (in some controller or main file):
async function main() {
  const userService = new UserService();
  await userService.onModuleInit();

  const newUser = await userService.createUser('John Doe', 'john@example.com');
  console.log('Created user:', newUser);

  const users = await userService.getAllUsers();
  console.log('All users:', users);

  await userService.onModuleDestroy();
}

main();
OutputSuccess
Important Notes

Always connect to the database before queries and disconnect after to avoid resource leaks.

Prisma Client methods return promises, so use async/await or .then() to handle results.

Use the Prisma schema file to define your database models before generating Prisma Client.

Summary

Prisma Client lets you work with your database using simple JavaScript calls.

Use it in NestJS by importing and creating a PrismaClient instance.

Remember to connect and disconnect Prisma Client properly in your app lifecycle.