Careeroza
CRUD with Prisma
ProductsService with Prisma
src/products/products.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { CreateProductDto } from './dto/create-product.dto';
import { UpdateProductDto } from './dto/update-product.dto';
@Injectable()
export class ProductsService {
constructor(private readonly prisma: PrismaService) {}
findAll(category?: string) {
return this.prisma.product.findMany({
where: category ? { category: { slug: category } } : undefined,
include: { category: { select: { slug: true, name: true } } },
orderBy: { createdAt: 'desc' },
take: 20,
});
}
async findOne(id: number) {
const product = await this.prisma.product.findUnique({ where: { id }, include: { category: true } });
if (!product) throw new NotFoundException(`Product ${id} not found`);
return product;
}
create(dto: CreateProductDto & { categoryId: number }) {
return this.prisma.product.create({ data: dto });
}
async update(id: number, dto: UpdateProductDto) {
try {
return await this.prisma.product.update({ where: { id }, data: dto });
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2025') {
throw new NotFoundException(`Product ${id} not found`);
}
throw e;
}
}
remove(id: number) {
return this.prisma.product.delete({ where: { id } });
}
}The Response
Example
Note that Prisma returns Decimal values, which serialise to JSON as strings:
curl "http://localhost:3000/products?category=audio"Example output
[{"id":7,"name":"boAt Airdopes 141","description":null,"price":"1299","stock":120,"categoryId":2,"createdAt":"2026-01-15T10:00:00.000Z","updatedAt":"2026-01-15T10:00:00.000Z","category":{"slug":"audio","name":"Audio"}}]Tip: Prisma queries are fully typed: product.category.slug exists only because you wrote include: { category: ... }. Remove the include and TypeScript shows an error.