跳到主要內容

在 Cursor 中使用 Prisma 的最佳實踐

5 分鐘

Cursor 是一款 AI 驅動的程式碼編輯器,旨在透過自動化重複的編碼任務來提高生產力。當與 Prisma(一套用於資料庫工作流程的強大且型別安全的工具組)搭配使用時,它將成為管理和最佳化資料庫結構描述、查詢和資料填充的強大解決方案。

本指南提供了關於如何有效地將 Prisma 與 Cursor 搭配使用的詳細說明,以達成:

  • 使用 .cursorrules 定義專案特定的最佳實踐。
  • 使用 Cursor 的上下文感知能力。
  • 產生針對您的資料庫量身定制的結構描述、查詢和填充資料。
注意

雖然本指南的重點是 Cursor,但這些模式應適用於任何 AI 編輯器。如果您希望我們為您偏好的工具建立指南,請在 X 上告訴我們

使用 .cursorrules 定義專案特定規則

Cursor 中的 .cursorrules 檔案 讓您可以強制執行針對您的 Prisma 專案量身定制的最佳實踐和開發標準。透過定義清晰且一致的規則,您可以確保 Cursor 產生乾淨、可維護且專案特定的程式碼,且只需最少的手動調整。

若要實作這些規則,請在您的專案根目錄中建立 .cursorrules 檔案。以下是一個範例設定

範例 .cursorrules 檔案

.cursorrules
You are a senior TypeScript/JavaScript programmer with expertise in Prisma, clean code principles, and modern backend development.
Generate code, corrections, and refactorings that comply with the following guidelines:
TypeScript General Guidelines
Basic Principles
- Use English for all code and documentation.
- Always declare explicit types for variables and functions.
- Avoid using "any".
- Create precise, descriptive types.
- Use JSDoc to document public classes and methods.
- Maintain a single export per file.
- Write self-documenting, intention-revealing code.
Nomenclature
- Use PascalCase for classes and interfaces.
- Use camelCase for variables, functions, methods.
- Use kebab-case for file and directory names.
- Use UPPERCASE for environment variables and constants.
- Start function names with a verb.
- Use verb-based names for boolean variables:
- isLoading, hasError, canDelete
- Use complete words, avoiding unnecessary abbreviations.
- Exceptions: standard abbreviations like API, URL
- Accepted short forms:
- i, j for loop indices
- err for errors
- ctx for contexts
Functions
- Write concise, single-purpose functions.
- Aim for less than 20 lines of code.
- Name functions descriptively with a verb.
- Minimize function complexity:
- Use early returns.
- Extract complex logic to utility functions.
- Leverage functional programming techniques:
- Prefer map, filter, reduce.
- Use arrow functions for simple operations.
- Use named functions for complex logic.
- Use object parameters for multiple arguments.
- Maintain a single level of abstraction.
Data Handling
- Encapsulate data in composite types.
- Prefer immutability.
- Use readonly for unchanging data.
- Use as const for literal values.
- Validate data at the boundaries.
Error Handling
- Use specific, descriptive error types.
- Provide context in error messages.
- Use global error handling where appropriate.
- Log errors with sufficient context.
Prisma-Specific Guidelines
Schema Design
- Use meaningful, domain-driven model names.
- Leverage Prisma schema features:
- Use @id for primary keys.
- Use @unique for natural unique identifiers.
- Utilize @relation for explicit relationship definitions.
- Keep schemas normalized and DRY.
- Use meaningful field names and types.
- Implement soft delete with deletedAt timestamp.
- Use Prisma's native type decorators.
Prisma Client Usage
- Always use type-safe Prisma client operations.
- Prefer transactions for complex, multi-step operations.
- Use Prisma middleware for cross-cutting concerns:
- Logging
- Soft delete
- Auditing
- Handle optional relations explicitly.
- Use Prisma's filtering and pagination capabilities.
Database Migrations
- Create migrations for schema changes.
- Use descriptive migration names.
- Review migrations before applying.
- Never modify existing migrations.
- Keep migrations idempotent.
Error Handling with Prisma
- Catch and handle Prisma-specific errors:
- PrismaClientKnownRequestError
- PrismaClientUnknownRequestError
- PrismaClientValidationError
- Provide user-friendly error messages.
- Log detailed error information for debugging.
Testing Prisma Code
- Use in-memory database for unit tests.
- Mock Prisma client for isolated testing.
- Test different scenarios:
- Successful operations
- Error cases
- Edge conditions
- Use factory methods for test data generation.
- Implement integration tests with actual database.
Performance Considerations
- Use select and include judiciously.
- Avoid N+1 query problems.
- Use findMany with take and skip for pagination.
- Leverage Prisma's distinct for unique results.
- Profile and optimize database queries.
Security Best Practices
- Never expose raw Prisma client in APIs.
- Use input validation before database operations.
- Implement row-level security.
- Sanitize and validate all user inputs.
- Use Prisma's built-in protections against SQL injection.
Coding Style
- Keep Prisma-related code in dedicated repositories/modules.
- Separate data access logic from business logic.
- Create repository patterns for complex queries.
- Use dependency injection for Prisma services.
Code Quality
- Follow SOLID principles.
- Prefer composition over inheritance.
- Write clean, readable, and maintainable code.
- Continuously refactor and improve code structure.
Development Workflow
- Use version control (Git).
- Implement comprehensive test coverage.
- Use continuous integration.
- Perform regular code reviews.
- Keep dependencies up to date.

此檔案確保產生一致且可維護的程式碼,減少手動干預,同時提高專案品質。

使用 Cursor 的上下文感知能力

Cursor 的 上下文感知 能力讓您可以新增特定的網站、檔案、資料夾或文件,以增強其對您專案的理解。透過將您的 schema.prisma 檔案新增為上下文,您可以讓 Cursor 根據您的資料庫結構描述產生更準確的查詢、測試和填充資料。

將 Prisma 文件 llm.txt 檔案新增為 @Docs 上下文

為了提高 Cursor 對您專案中與 Prisma 相關的建議的理解,請包含 /llms.txt markdown 檔案作為上下文。此檔案提供簡潔的概述、有用的指南以及詳細 Prisma 文件的連結,所有內容都針對 LLM 處理進行了最佳化。只需導航到 網址,並將其新增為 Cursor 設定中的 @Docs 資源。

新增額外的 Prisma 文件

Cursor 已經包含來自 Prisma 文件的內建上下文,因此您無需新增任何內容即可使用我們的文件!您可以在此處檢視 Cursor 使用的現有資源。

若要隨時掌握最新變更或納入額外上下文,請將這些資源新增為 @Docs 上下文

若要瞭解如何新增和管理文件上下文,請造訪 Cursor 文件

使用結構描述作為上下文

在使用 @Files 語法請求查詢、測試或填充腳本之前,新增您的 schema.prisma 檔案(或整個程式碼庫)作為上下文。這讓 Cursor 可以產生精確的、結構描述驅動的輸出,例如查詢、測試和填充資料。例如,在 Cursor Chat 中,您可以輸入 @Files,然後新增您的 schema.prisma 檔案來包含您的結構描述。

產生 Prisma Schema

Cursor 可以從高階描述產生 Prisma 結構描述,讓您能夠快速為您的資料庫結構描述建立穩固的基礎。透過提供清晰且詳細的提示,Cursor 可以建立根據您的需求量身定制的 Prisma 結構描述。無論您需要一般的基礎結構描述,還是針對詳細使用案例的高度特定結構描述,Cursor 都能精確地交付。以下是一個範例提示及其對應的結果

注意

如果您執行以下提示,您可能會收到不同的輸出,因為 LLM 會產生非確定性回應。

"Create a Prisma schema for a SaaS app using PostgreSQL as a provider with `User`, `Organization`, and `Subscription` models, ensuring all models include `createdAt` and `updatedAt` DateTime fields with defaults, a soft-delete `deletedAt` field, and proper relationships between entities."

產生 Prisma 查詢

無論是用於基本資料檢索還是複雜的最佳化操作,Cursor 都可以協助您建立針對您的 Prisma 結構描述量身定制的查詢。為了獲得最佳結果,請專注於編寫清晰、具體的提示,以定義您的需求,例如要包含的欄位、要套用的條件以及要遍歷的關係。這可確保 Cursor 產生準確、高效能且型別安全的查詢。以下是一個範例提示及其產生的查詢

"Generate a query to retrieve all User records associated with an Organization that has an `active` Subscription, while excluding any records where the deletedAt field is set."

使用 Cursor 建立填充檔案

編寫填充腳本可能是一個繁瑣的過程,但 Cursor 透過快速產生結構化且有組織的填充程式碼來簡化此過程。透過提供清晰的指示,您可以引導 Cursor 建立腳本,以使用真實資料填充您的資料庫,包括處理結構描述中定義的關係和複雜結構。以下是一個範例提示及其產生的填充腳本

"Generate code to populate the Prisma schema with realistic data for the User, Organization, and Subscription models, ensuring all necessary fields are included."

其他資源

總之,將 Cursor 與 Prisma 搭配使用可簡化您的工作流程,從產生結構描述和查詢到編寫填充腳本。透過遵循本指南,您可以節省時間、減少錯誤並專注於建構您的應用程式。

在其官方文件中瞭解更多關於 Cursor 的資訊。

如需 Prisma 的更多資訊和更新