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

📋 指挥者协议

  1. Schema First: Always define the data model in
    convex/schema.ts
    before writing functions.
  2. Auth Validation: Every public function MUST validate
    ctx.auth.getUserIdentity()
    .
  3. Indexing: Never use
    .filter()
    on unbounded datasets; define and use
    .withIndex()
    .
  4. Transactionality: Group related database operations into a single mutation to ensure consistency.

  1. Schema优先:编写函数前,务必在
    convex/schema.ts
    中定义数据模型。
  2. 权限验证:每个公共函数必须验证
    ctx.auth.getUserIdentity()
  3. 索引规则:切勿在无界数据集上使用
    .filter()
    ;应定义并使用
    .withIndex()
  4. 事务性:将相关数据库操作分组到单个变更中,以确保一致性。

🛠️ 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
    ConvexError
    with structured data for all unauthorized attempts.
  • Pattern: Use "unguessable IDs" or
    userId
    from
    getUserIdentity()
    for all sensitive queries.
虽然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
    paginationOpts
    for all list-style queries expected to grow beyond 100 items.
  • 规则:查询默认是反应式的。最小化返回数据的范围以减少带宽消耗。
  • 分页:对于预期会增长到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)

🛡️ 禁忌清单(反模式)

  1. DO NOT use
    npx convex deploy
    unless specifically asked; use
    npx convex dev
    for local development.
  2. DO NOT use
    Array.filter()
    inside a query handler for large datasets. Use
    ctx.db.query(...).withIndex(...)
    .
  3. DO NOT pass
    userId
    as a plain argument from the client if it's used for security; always derive it from
    ctx.auth.getUserIdentity()
    .
  4. DO NOT use
    ctx.runQuery
    or
    ctx.runMutation
    inside an action if the logic can be moved to a single mutation. It breaks transactionality.
  5. DO NOT ignore return validators. Always specify
    returns: v.any()
    or a strict object schema.

  1. 禁止使用
    npx convex deploy
    ,除非特别要求;本地开发请使用
    npx convex dev
  2. 禁止在查询处理程序中对大型数据集使用
    Array.filter()
    。请使用
    ctx.db.query(...).withIndex(...)
  3. 禁止如果
    userId
    用于安全验证,从客户端传递纯参数形式的
    userId
    ;务必从
    ctx.auth.getUserIdentity()
    中获取。
  4. 禁止如果逻辑可以移至单个变更中,在action内使用
    ctx.runQuery
    ctx.runMutation
    。这会破坏事务性。
  5. 禁止忽略返回验证器。务必指定
    returns: v.any()
    或严格的对象 schema。

📂 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

🛠️ 专用工具与脚本

  • scripts/sync-schema.ts
    : Automatically generates Zod schemas from your Convex data model.
  • scripts/audit-indexes.py
    : Scans your functions to find queries without proper indexing.

  • scripts/sync-schema.ts
    :从Convex数据模型自动生成Zod schema。
  • scripts/audit-indexes.py
    :扫描函数以查找未正确使用索引的查询。

🎓 Learning Resources

🎓 学习资源