Chuyển đến nội dung
Skillpedia
API và máy chủ (backend)280k · #224

prisma-patterns

Skill này làm gì

Hướng dẫn này giúp bạn dùng Prisma ORM hiệu quả hơn trong dự án lập trình. Nó chỉ thực hành tốt nhất để tổ chức dữ liệu, viết truy vấn nhanh và tránh các cạm bẫy thường gặp.

Khi nào nên dùng

  • ✓Khi tạo hoặc thay đổi cấu trúc cơ sở dữ liệu bằng Prisma.
  • ✓Khi viết code lấy hoặc lưu thông tin từ cơ sở dữ liệu.
  • ✓Khi gỡ lỗi các lỗi trong giao dịch hoặc khi cập nhật nhiều dữ liệu cùng lúc.

Liên kết skill

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/prisma-patterns/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/prisma-patterns/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để các truy vấn cơ sở dữ liệu của tôi nhanh và an toàn?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Hướng dẫn giải thích cách thiết lập cơ sở dữ liệu, chọn cách lấy dữ liệu tốt nhất và dùng giao dịch an toàn. Nó cũng cảnh báo về các cạm bẫy thường gặp có thể gây chậm hoặc lỗi.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

Prisma Patterns

Production patterns and non-obvious traps for Prisma ORM in TypeScript backends.

Check your version before applying patterns. The Prisma API surface has evolved across major releases:

npx prisma --version

Notable API differences across versions:

  • relationJoins can load relations via JOIN rather than separate queries, but may cause row explosion on large 1:N relations or deep include — benchmark both approaches
  • omit field modifier and prisma.$extends Client Extensions API were added
  • Newer installs: the package may be named prisma instead of @prisma/client; PrismaClient may require a driver adapter (e.g. @prisma/adapter-pg); datasource.url may live in prisma.config.ts instead of schema.prisma
  • CLI commands (migrate dev, migrate deploy, generate) are unchanged across versions

When to Activate

  • Designing or modifying Prisma schema models and relations
  • Writing queries, transactions, or pagination logic
  • Using updateMany, deleteMany, or any bulk operation
  • Running or planning database migrations
  • Deploying to serverless environments (Vercel, Lambda, Cloudflare Workers)
  • Implementing soft delete or multi-tenant row filtering

Core Concepts

ID Strategy

Strategy Use When Avoid When
@default(cuid()) Default choice — URL-safe, sortable, no collisions Sequential IDs needed for external systems
@default(uuid()) Interoperability with non-Prisma systems required High-write tables (random UUIDs fragment B-tree indexes)
@default(autoincrement()) Internal join tables, audit logs Public-facing IDs (exposes record count)

Schema Defaults

model User {
  id        String    @id @default(cuid())
  email     String    @unique  // @unique already creates an index — no @@index needed
  name      String
  role      Role      @default(USER)
  posts     Post[]
  createdAt DateTime  @default(now())
  updatedAt DateTime  @updatedAt
  deletedAt DateTime?

  @@index([createdAt])
  @@index([deletedAt, createdAt]) // composite for soft-delete + sort queries
}
  • Add @@index on every foreign key and column used in WHERE or ORDER BY.
  • Declare deletedAt DateTime? upfront when soft delete is a foreseeable requirement — adding it later requires a migration on a live table.
  • updatedAt @updatedAt is set automatically by Prisma on update and upsert only (see Anti-Patterns for bulk update trap).

include vs select

include select
Returns All scalar fields + specified relations Only specified fields
Use when You need most fields plus a relation Hot paths, large tables, avoiding over-fetch
Performance May over-fetch on wide tables Minimal payload, faster on large datasets
Prisma 5 note Uses JOIN by default (relationJoins) Same
// include — all columns + relation
const user = await prisma.user.findUnique({
  where: { id },
  include: { posts: { select: { id: true, title: true } } },
});

// select — explicit allowlist
const user = await prisma.user.findUnique({
  where: { id },
  select: { id: true, email: true, name: true },
});

Never return raw Prisma entities from API responses — map to response DTOs to control exposed fields:

// BAD: leaks passwordHash, deletedAt, internal fields
return await prisma.user.findUniqueOrThrow({ where: { id } });

// GOOD: explicit DTO mapping
const user = await prisma.user.findUniqueOrThrow({ where: { id } });
return { id: user.id, name: user.name, email: user.email };

Transaction Form Selection

Situation Use
Independent operations, no inter-dependency Array form
Later step depends on earlier result Interactive form
External calls (email, HTTP) involved Outside transaction entirely
// Array form — batched in one round trip
const [user, post] = await prisma.$transaction([
  prisma.user.update({ where: { id }, data: { name } }),
  prisma.post.create({ data: { title, authorId: id } }),
]);

// Interactive form — use tx client only, never the outer prisma client
const post = await prisma.$transaction(async (tx) => {
  const user = await tx.user.findUniqueOrThrow({ where: { id } });
  if (user.role !== 'ADMIN') throw new Error('Forbidden');
  return tx.post.create({ data: { title, authorId: user.id } });
});

PrismaClient Singleton

…

Câu hỏi thường gặp

Prisma ORM là gì?

Prisma ORM là công cụ giúp lập trình viên làm việc với cơ sở dữ liệu dễ dàng và an toàn hơn, đặc biệt trong dự án dùng TypeScript.

Vì sao nên quan tâm đến 'mẫu' và 'cạm bẫy'?

Tuân theo các mẫu tốt và tránh cạm bẫy giúp ứng dụng nhanh, ổn định và ít lỗi hơn, tiết kiệm thời gian bảo trì.

'Giao dịch' (transaction) là gì?

Giao dịch giống như một gói các thao tác cơ sở dữ liệu. Hoặc tất cả thao tác trong gói đều thành công, hoặc không thao tác nào được thực hiện, đảm bảo tính nhất quán của dữ liệu.

Chi tiết

Mô tả gốc của tác giả

Prisma ORM patterns for TypeScript backends — schema design, query optimization, transactions, pagination, and critical traps like updateMany returning count not records, $transaction timeouts, migrate dev resetting the DB, @updatedAt skipped on bulk writes, and serverless connection exhaustion. Use when writing a Prisma schema or query, or debugging transactions, migrations, or serverless connect

repo: affaan-m/ECC

Độ phổ biến

Sao GitHub
280k
Vị trí xếp hạng
#224
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự