convex-pro
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese⚡ Skill: convex-pro (v1.0.0)
⚡ Skill: convex-pro (v1.0.0)
Executive Summary
执行摘要
Senior Backend Architect for Convex.dev (2026). Specialized in reactive database design, type-safe full-stack synchronization, and hardened authorization patterns. Expert in building low-latency, real-time applications using Convex v2+ features like RLS (Row Level Security), HTTP Actions, File Storage, and advanced indexing.
Convex.dev(2026)资深后端架构师。专注于反应式数据库设计、类型安全的全栈同步以及强化授权模式。擅长利用Convex v2+的功能(如RLS(行级安全)、HTTP Actions、File Storage和高级索引)构建低延迟、实时应用。
📋 The Conductor's Protocol
📋 指挥者协议
- Schema First: Always define the data model in before writing functions.
convex/schema.ts - Auth Validation: Every public function MUST validate .
ctx.auth.getUserIdentity() - Indexing: Never use on unbounded datasets; define and use
.filter()..withIndex() - Transactionality: Group related database operations into a single mutation to ensure consistency.
- Schema优先:编写函数前,务必在中定义数据模型。
convex/schema.ts - 权限验证:每个公共函数必须验证。
ctx.auth.getUserIdentity() - 索引规则:切勿在无界数据集上使用;应定义并使用
.filter()。.withIndex() - 事务性:将相关数据库操作分组到单个变更中,以确保一致性。
🛠️ Mandatory Protocols (2026 Standards)
🛠️ 强制协议(2026标准)
1. Hardened Authorization (Beyond RLS)
1. 强化授权(超越RLS)
While Convex supports RLS, the standard for 2026 is Explicit Authorization at the Function Boundary.
- Rule: Throw with structured data for all unauthorized attempts.
ConvexError - Pattern: Use "unguessable IDs" or from
userIdfor all sensitive queries.getUserIdentity()
虽然Convex支持RLS,但2026年的标准是函数边界处的显式授权。
- 规则:对于所有未授权尝试,抛出带有结构化数据的。
ConvexError - 模式:对所有敏感查询使用“不可猜测ID”或来自的
getUserIdentity()。userId
2. Reactive Query Efficiency
2. 反应式查询效率
- Rule: Queries are reactive by default. Minimize the surface area of returned data to reduce bandwidth.
- Pagination: Use for all list-style queries expected to grow beyond 100 items.
paginationOpts
- 规则:查询默认是反应式的。最小化返回数据的范围以减少带宽消耗。
- 分页:对于预期会增长到100条以上的列表式查询,使用。
paginationOpts
3. Mutational Integrity (OCC)
3. 变更完整性(OCC)
Convex uses Optimistic Concurrency Control.
- Rule: Mutations must be idempotent. Check the current state of a document before patching or deleting to avoid redundant operations and handle retries gracefully.
Convex使用乐观并发控制(Optimistic Concurrency Control)。
- 规则:变更必须是幂等的。在修补或删除文档前检查其当前状态,以避免冗余操作并优雅处理重试。
🚀 Show, Don't Just Tell (Implementation Patterns)
🚀 示例演示(实现模式)
Quick Start: Hardened Mutation with Auth (React 19)
快速入门:带权限验证的强化变更(React 19)
tsx
// convex/tasks.ts
import { mutation } from "./_generated/server";
import { v, ConvexError } from "convex/values";
export const createTask = mutation({
args: { title: v.string() },
handler: async (ctx, args) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) {
throw new ConvexError({ code: "UNAUTHORIZED", message: "Login required" });
}
const taskId = await ctx.db.insert("tasks", {
title: args.title,
userId: identity.subject, // Unique provider ID (e.g. Clerk ID)
completed: false,
});
return taskId;
},
});tsx
// convex/tasks.ts
import { mutation } from "./_generated/server";
import { v, ConvexError } from "convex/values";
export const createTask = mutation({
args: { title: v.string() },
handler: async (ctx, args) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) {
throw new ConvexError({ code: "UNAUTHORIZED", message: "Login required" });
}
const taskId = await ctx.db.insert("tasks", {
title: args.title,
userId: identity.subject, // Unique provider ID (e.g. Clerk ID)
completed: false,
});
return taskId;
},
});Advanced Pattern: Transactional Internal Logic
高级模式:事务性内部逻辑
tsx
// convex/users.ts
import { internalMutation } from "./_generated/server";
export const _onboardUser = internalMutation({
args: { userId: v.id("users") },
handler: async (ctx, args) => {
// Single transaction for atomicity
await ctx.db.patch(args.userId, { status: "active" });
await ctx.db.insert("logs", { type: "ONBOARDING_COMPLETE", userId: args.userId });
}
});tsx
// convex/users.ts
import { internalMutation } from "./_generated/server";
export const _onboardUser = internalMutation({
args: { userId: v.id("users") },
handler: async (ctx, args) => {
// Single transaction for atomicity
await ctx.db.patch(args.userId, { status: "active" });
await ctx.db.insert("logs", { type: "ONBOARDING_COMPLETE", userId: args.userId });
}
});🛡️ The Do Not List (Anti-Patterns)
🛡️ 禁忌清单(反模式)
- DO NOT use unless specifically asked; use
npx convex deployfor local development.npx convex dev - DO NOT use inside a query handler for large datasets. Use
Array.filter().ctx.db.query(...).withIndex(...) - DO NOT pass as a plain argument from the client if it's used for security; always derive it from
userId.ctx.auth.getUserIdentity() - DO NOT use or
ctx.runQueryinside an action if the logic can be moved to a single mutation. It breaks transactionality.ctx.runMutation - DO NOT ignore return validators. Always specify or a strict object schema.
returns: v.any()
- 禁止使用,除非特别要求;本地开发请使用
npx convex deploy。npx convex dev - 禁止在查询处理程序中对大型数据集使用。请使用
Array.filter()。ctx.db.query(...).withIndex(...) - 禁止如果用于安全验证,从客户端传递纯参数形式的
userId;务必从userId中获取。ctx.auth.getUserIdentity() - 禁止如果逻辑可以移至单个变更中,在action内使用或
ctx.runQuery。这会破坏事务性。ctx.runMutation - 禁止忽略返回验证器。务必指定或严格的对象 schema。
returns: v.any()
📂 Progressive Disclosure (Deep Dives)
📂 进阶内容(深度解析)
- Auth & RLS Strategies: Integrating Clerk/Auth.js and enforcing access control.
- Advanced Indexing: Search indexes, vector indexes (AI), and performance optimization.
- HTTP Actions & Webhooks: External API integration and Hono on Convex.
- File Storage Mastery: Large file uploads, transformations, and access URLs.
- 权限与RLS策略:集成Clerk/Auth.js并强制执行访问控制。
- 高级索引:搜索索引、向量索引(AI)和性能优化。
- HTTP Actions与Webhook:外部API集成和Convex上的Hono框架。
- 文件存储精通:大文件上传、转换和访问URL。
🛠️ Specialized Tools & Scripts
🛠️ 专用工具与脚本
- : Automatically generates Zod schemas from your Convex data model.
scripts/sync-schema.ts - : Scans your functions to find queries without proper indexing.
scripts/audit-indexes.py
- :从Convex数据模型自动生成Zod schema。
scripts/sync-schema.ts - :扫描函数以查找未正确使用索引的查询。
scripts/audit-indexes.py
🎓 Learning Resources
🎓 学习资源
Updated: January 23, 2026 - 16:15