convex-best-practices

convex-best-practices

熱門

建構可上線 Convex 應用程式的指南,涵蓋函式組織、查詢模式、驗證、TypeScript 使用、錯誤處理以及 Convex 設計哲學

400星標
31分支
更新於 2026/2/6
SKILL.md
唯讀
名稱
convex-best-practices
描述

建構可上線 Convex 應用程式的指南,涵蓋函式組織、查詢模式、驗證、TypeScript 使用、錯誤處理以及 Convex 設計哲學

Convex 最佳實務

遵循已建立的模式來建構可上線的 Convex 應用程式,包括函式組織、查詢最佳化、驗證、TypeScript 使用和錯誤處理。

程式碼品質

此技能中的所有模式皆符合 @convex-dev/eslint-plugin。請安裝它以在建置時進行驗證:

npm i @convex-dev/eslint-plugin --save-dev
// eslint.config.js
import { defineConfig } from "eslint/config";
import convexPlugin from "@convex-dev/eslint-plugin";

export default defineConfig([
  ...convexPlugin.configs.recommended,
]);

此套件強制執行四條規則:

規則 強制內容
no-old-registered-function-syntax 使用 handler 的物件語法
require-argument-validators 所有函式加上 args: {}
explicit-table-ids 資料庫操作中指定資料表名稱
import-wrong-runtime 禁止在 Convex 執行環境中引入 Node 模組

文件:https://docs.convex.dev/eslint

文件來源

在實作之前,不要假設;請取得最新文件:

指示

Convex 的禪意

  1. Convex 處理困難的部分 - 讓 Convex 處理快取、即時同步和一致性
  2. 函式即 API - 將你的函式設計為應用程式的介面
  3. Schema 即真理 - 在 schema.ts 中明確定義資料模型
  4. TypeScript 無所不在 - 善用端到端的型別安全
  5. 查詢是反應式的 - 以訂閱而非請求的方式思考

函式組織

按領域組織你的 Convex 函式:

// convex/users.ts - 使用者相關函式
import { query, mutation } from "./_generated/server";
import { v } from "convex/values";

export const get = query({
  args: { userId: v.id("users") },
  returns: v.union(
    v.object({
      _id: v.id("users"),
      _creationTime: v.number(),
      name: v.string(),
      email: v.string(),
    }),
    v.null(),
  ),
  handler: async (ctx, args) => {
    return await ctx.db.get("users", args.userId);
  },
});

引數與回傳值驗證

永遠為引數和回傳型別定義驗證器:

export const createTask = mutation({
  args: {
    title: v.string(),
    description: v.optional(v.string()),
    priority: v.union(v.literal("low"), v.literal("medium"), v.literal("high")),
  },
  returns: v.id("tasks"),
  handler: async (ctx, args) => {
    return await ctx.db.insert("tasks", {
      title: args.title,
      description: args.description,
      priority: args.priority,
      completed: false,
      createdAt: Date.now(),
    });
  },
});

查詢模式

使用索引而非篩選器來進行高效查詢:

// 含索引的 Schema
export default defineSchema({
  tasks: defineTable({
    userId: v.id("users"),
    status: v.string(),
    createdAt: v.number(),
  })
    .index("by_user", ["userId"])
    .index("by_user_and_status", ["userId", "status"]),
});

// 使用索引查詢
export const getTasksByUser = query({
  args: { userId: v.id("users") },
  returns: v.array(
    v.object({
      _id: v.id("tasks"),
      _creationTime: v.number(),
      userId: v.id("users"),
      status: v.string(),
      createdAt: v.number(),
    }),
  ),
  handler: async (ctx, args) => {
    return await ctx.db
      .query("tasks")
      .withIndex("by_user", (q) => q.eq("userId", args.userId))
      .order("desc")
      .collect();
  },
});

錯誤處理

使用 ConvexError 處理面向使用者的錯誤:

import { ConvexError } from "convex/values";

export const updateTask = mutation({
  args: {
    taskId: v.id("tasks"),
    title: v.string(),
  },
  returns: v.null(),
  handler: async (ctx, args) => {
    const task = await ctx.db.get("tasks", args.taskId);

    if (!task) {
      throw new ConvexError({
        code: "NOT_FOUND",
        message: "找不到任務",
      });
    }

    await ctx.db.patch("tasks", args.taskId, { title: args.title });
    return null;
  },
});

避免寫入衝突(樂觀並行控制)

Convex 使用 OCC。遵循以下模式以最小化衝突:

// 良好:使 mutation 具有冪等性
export const completeTask = mutation({
  args: { taskId: v.id("tasks") },
  returns: v.null(),
  handler: async (ctx, args) => {
    const task = await ctx.db.get("tasks", args.taskId);

    // 如果已完成則提前返回(冪等)
    if (!task || task.status === "completed") {
      return null;
    }

    await ctx.db.patch("tasks", args.taskId, {
      status: "completed",
      completedAt: Date.now(),
    });
    return null;
  },
});

// 良好:盡可能直接 patch 而不先讀取
export const updateNote = mutation({
  args: { id: v.id("notes"), content: v.string() },
  returns: v.null(),
  handler: async (ctx, args) => {
    // 直接 patch - 若文件不存在 ctx.db.patch 會拋出錯誤
    await ctx.db.patch("notes", args.id, { content: args.content });
    return null;
  },
});

// 良好:對並行獨立更新使用 Promise.all
export const reorderItems = mutation({
  args: { itemIds: v.array(v.id("items")) },
  returns: v.null(),
  handler: async (ctx, args) => {
    const updates = args.itemIds.map((id, index) =>
      ctx.db.patch("items", id, { order: index }),
    );
    await Promise.all(updates);
    return null;
  },
});

TypeScript 最佳實務

import { Id, Doc } from "./_generated/dataModel";

// 使用 Id 型別表示文件參考
type UserId = Id<"users">;

// 使用 Doc 型別表示完整文件
type User = Doc<"users">;

// 正確定義 Record 型別
const userScores: Record<Id<"users">, number> = {};

內部函式 vs 公開函式

// 公開函式 - 暴露給客戶端
export const getUser = query({
  args: { userId: v.id("users") },
  returns: v.union(
    v.null(),
    v.object({
      /* ... */
    }),
  ),
  handler: async (ctx, args) => {
    // ...
  },
});

// 內部函式 - 僅能從其他 Convex 函式呼叫
export const _updateUserStats = internalMutation({
  args: { userId: v.id("users") },
  returns: v.null(),
  handler: async (ctx, args) => {
    // ...
  },
});

範例

完整 CRUD 模式

// convex/tasks.ts
import { query, mutation } from "./_generated/server";
import { v } from "convex/values";
import { ConvexError } from "convex/values";

const taskValidator = v.object({
  _id: v.id("tasks"),
  _creationTime: v.number(),
  title: v.string(),
  completed: v.boolean(),
  userId: v.id("users"),
});

export const list = query({
  args: { userId: v.id("users") },
  returns: v.array(taskValidator),
  handler: async (ctx, args) => {
    return await ctx.db
      .query("tasks")
      .withIndex("by_user", (q) => q.eq("userId", args.userId))
      .collect();
  },
});

export const create = mutation({
  args: {
    title: v.string(),
    userId: v.id("users"),
  },
  returns: v.id("tasks"),
  handler: async (ctx, args) => {
    return await ctx.db.insert("tasks", {
      title: args.title,
      completed: false,
      userId: args.userId,
    });
  },
});

export const update = mutation({
  args: {
    taskId: v.id("tasks"),
    title: v.optional(v.string()),
    completed: v.optional(v.boolean()),
  },
  returns: v.null(),
  handler: async (ctx, args) => {
    const { taskId, ...updates } = args;

    // 移除 undefined 值
    const cleanUpdates = Object.fromEntries(
      Object.entries(updates).filter(([_, v]) => v !== undefined),
    );

    if (Object.keys(cleanUpdates).length > 0) {
      await ctx.db.patch("tasks", taskId, cleanUpdates);
    }
    return null;
  },
});

export const remove = mutation({
  args: { taskId: v.id("tasks") },
  returns: v.null(),
  handler: async (ctx, args) => {
    await ctx.db.delete("tasks", args.taskId);
    return null;
  },
});

最佳實務

  • 除非明確指示,否則不要執行 npx convex deploy
  • 除非明確指示,否則不要執行任何 git 指令
  • 永遠為函式定義回傳驗證器
  • 對所有篩選資料的查詢使用索引
  • 使 mutation 具有冪等性以優雅處理重試
  • 使用 ConvexError 處理面向使用者的錯誤訊息
  • 按領域組織函式(users.ts、tasks.ts 等)
  • 對敏感操作使用內部函式
  • 善用 TypeScript 的 Id 和 Doc 型別

常見陷阱

  1. 使用 filter 而非 withIndex - 永遠定義索引並使用 withIndex
  2. 缺少回傳驗證器 - 永遠指定 returns 欄位
  3. 非冪等的 mutation - 在更新前檢查當前狀態
  4. 不必要地先讀取再 patch - 盡可能直接 patch
  5. 未處理 null 回傳 - 文件 ID 可能不存在

參考資料