Prisma Client helps you talk to your database easily. It lets you get, add, change, or delete data without writing complex SQL.
Prisma Client usage in 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.
const allUsers = await prisma.user.findMany();const newUser = await prisma.user.create({ data: { name: 'Anna', email: 'anna@example.com' } });
const updatedUser = await prisma.user.update({ where: { id: 1 }, data: { name: 'Anna Smith' } });
const deletedUser = await prisma.user.delete({ where: { id: 1 } });
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.
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();
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.
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.