关于 convex-best-practices
convex-best-practices 是面向 Convex 应用开发者的编码技能,涵盖函数设计、验证、查询、TypeScript 和错误处理等实践。
主要功能
- 01按领域组织函数
- 02验证参数与返回值
- 03使用索引执行查询
- 04用 ConvexError 处理错误
- 05通过幂等 mutation 减少写冲突
- 06使用 TypeScript 的 Id 和 Doc 类型
适用场景
- 01设计 Convex 函数 API
- 02提升查询效率
- 03添加验证与错误处理
- 04减少 mutation 冲突
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ julianromli/ ai-skills --skill convex-best-practices安装后在 Claude Code 中输入/convex-best-practices确认已加载。
详细介绍
Convex 最佳实践
遵循成熟的函数组织、查询优化、验证、TypeScript 使用和错误处理模式,构建可用于生产环境的 Convex 应用。
代码质量
本技能中的所有模式都符合 @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 | 在 db 操作中指定表名 |
import-wrong-runtime | Convex 运行时中不得导入 Node 模块 |
文档:https://docs.convex.dev/eslint
文档来源
实现之前,请勿想当然;请获取最新文档:
- 主要文档:https://docs.convex.dev/understanding/best-practices/
- 错误处理:https://docs.convex.dev/functions/error-handling
- 写入冲突:https://docs.convex.dev/error#1
- 更全面的背景信息:https://docs.convex.dev/llms.txt
指南
Convex 之道
- Convex 负责处理难题 - 让 Convex 处理缓存、实时同步和一致性
- 函数就是 API - 将函数设计为应用的接口
- Schema 是事实依据 - 在 schema.ts 中明确定义数据模型
- 全面使用 TypeScript - 利用端到端类型安全
- 查询具有响应性 - 从订阅而非请求的角度思考
函数组织
按领域组织 Convex 函数:
// convex/users.ts - User-related functions
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 with index
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"]),
});
// Query using index
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: "Task not found",
});
}
await ctx.db.patch("tasks", args.taskId, { title: args.title });
return null;
},
});
避免写入冲突(乐观并发控制)
Convex 使用 OCC。遵循以下模式以尽量减少冲突:
// GOOD: Make mutations idempotent
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);
// Early return if already complete (idempotent)
if (!task || task.status === "completed") {
return null;
}
await ctx.db.patch("tasks", args.taskId, {
status: "completed",
completedAt: Date.now(),
});
return null;
},
});
// GOOD: Patch directly without reading first when possible
export const updateNote = mutation({
args: { id: v.id("notes"), content: v.string() },
returns: v.null(),
handler: async (ctx, args) => {
// Patch directly - ctx.db.patch throws if document doesn't exist
await ctx.db.patch("notes", args.id, { content: args.content });
return null;
},
});
// GOOD: Use Promise.all for parallel independent updates
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";
// Use Id type for document references
type UserId = Id<"users">;
// Use Doc type for full documents
type User = Doc<"users">;
// Define Record types properly
const userScores: Record<Id<"users">, number> = {};
内部函数与公开函数
// Public function - exposed to clients
export const getUser = query({
args: { userId: v.id("users") },
returns: v.union(
v.null(),
v.object({
/* ... */
}),
),
handler: async (ctx, args) => {
// ...
},
});
// Internal function - only callable from other Convex functions
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;
// Remove undefined values
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 类型
常见问题
- 使用 filter 而不是 withIndex - 始终定义索引并使用 withIndex
- 缺少返回值验证器 - 始终指定 returns 字段
- mutation 不具备幂等性 - 更新前检查当前状态
- 不必要地在 patch 前读取数据 - 尽可能直接 patch
- 未处理 null 返回值 - 文档 ID 可能不存在
参考资料
评论
支持 Markdown