décembre 20, 20242 min de lecture
Database Patterns with Prisma ORM
Learn effective database patterns and best practices using Prisma ORM for scalable applications.
Learn effective database patterns and best practices using Prisma ORM for scalable applications.
Prisma has become the go-to ORM for TypeScript applications. Let's explore patterns that will make your database layer rock solid.
Initialize Prisma in your project:
npx prisma init
Define your schema:
model User {
id String @id @default(cuid())
email String @unique
name String?
posts Post[]
createdAt DateTime @default(now())
}
model Post {
id String @id @default(cuid())
title String
content String?
author User @relation(fields: [authorId], references: [id])
authorId String
}
Use select to fetch only needed fields:
const users = await prisma.user.findMany({
select: {
id: true,
name: true,
email: true,
},
});
Handle complex operations atomically:
const result = await prisma.$transaction(async (tx) => {
const user = await tx.user.create({
data: { email, name },
});
await tx.post.create({
data: { title: "Welcome!", authorId: user.id },
});
return user;
});
Implement soft deletes with a middleware:
prisma.$use(async (params, next) => {
if (params.action === "delete") {
params.action = "update";
params.args.data = { deletedAt: new Date() };
}
return next(params);
});
findFirst instead of findMany when expecting one result