0
0
NestJSframework~30 mins

CRUD with Prisma in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
CRUD with Prisma in NestJS
📖 Scenario: You are building a simple backend API for managing books in a library. Each book has a title and an author. You will use NestJS with Prisma to create, read, update, and delete books in the database.
🎯 Goal: Build a NestJS service that uses Prisma to perform CRUD operations on a Book model with title and author fields.
📋 What You'll Learn
Create a Prisma schema with a Book model having id, title, and author fields
Set up Prisma Client in NestJS
Implement CRUD methods in a NestJS service using Prisma Client
Use proper TypeScript types and async/await syntax
💡 Why This Matters
🌍 Real World
Backend developers often use Prisma with NestJS to build APIs that interact with databases easily and safely.
💼 Career
Knowing how to perform CRUD operations with Prisma in NestJS is a common requirement for backend developer roles.
Progress0 / 4 steps
1
Define the Prisma Book model
Create a Prisma schema file schema.prisma with a Book model that has an id field as an auto-incrementing integer primary key, a title field of type String, and an author field of type String.
NestJS
Need a hint?

Use model Book { ... } syntax. The id should be Int with @id and @default(autoincrement()).

2
Set up Prisma Client in NestJS service
In your NestJS service file books.service.ts, import PrismaClient from @prisma/client and create a private readonly property called prisma initialized with new PrismaClient().
NestJS
Need a hint?

Use import { PrismaClient } from '@prisma/client' and create private readonly prisma = new PrismaClient(); inside the service class.

3
Implement the createBook method
Add an async method called createBook in BooksService that takes a parameter data with title and author strings, and uses this.prisma.book.create to create and return a new book record.
NestJS
Need a hint?

Use async createBook(data: { title: string; author: string }) and call this.prisma.book.create({ data }).

4
Add findAll, updateBook, and deleteBook methods
In BooksService, add three async methods: findAll that returns all books using this.prisma.book.findMany(), updateBook that takes id and data to update a book using this.prisma.book.update, and deleteBook that takes id and deletes the book using this.prisma.book.delete.
NestJS
Need a hint?

Use findMany() for findAll, update({ where: { id }, data }) for updateBook, and delete({ where: { id } }) for deleteBook.