convex-backend

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Convex Backend Guidelines

Convex后端开发指南

Comprehensive guide for building Convex backends with TypeScript. Covers function syntax, validators, schemas, queries, mutations, actions, scheduling, and file storage.
这是使用TypeScript构建Convex后端的综合指南,涵盖函数语法、验证器、模式、查询、变更、操作、任务调度和文件存储。

When to Apply

适用场景

Reference these guidelines when:
  • Writing new Convex functions (queries, mutations, actions)
  • Defining database schemas and validators
  • Implementing real-time data fetching
  • Setting up cron jobs or scheduled functions
  • Working with file storage
  • Designing API structure
在以下场景中参考本指南:
  • 编写新的Convex函数(查询、变更、操作)
  • 定义数据库模式和验证器
  • 实现实时数据获取
  • 设置定时任务或调度函数
  • 处理文件存储
  • 设计API结构

Rule Categories

规则分类

CategoryImpactDescription
Function SyntaxCRITICALNew function syntax with args/returns/handler
ValidatorsCRITICALType-safe argument and return validation
Schema DesignHIGHTable definitions, indexes, system fields
Query PatternsHIGHEfficient data fetching with indexes
Mutation PatternsMEDIUMDatabase writes, patch vs replace
Action PatternsMEDIUMExternal API calls, Node.js runtime
SchedulingMEDIUMCrons and delayed function execution
File StorageLOWBlob storage and metadata
分类影响级别描述
函数语法关键包含参数/返回值/处理器的新函数语法
验证器关键类型安全的参数和返回值验证
模式设计表定义、索引、系统字段
查询模式使用索引的高效数据获取
变更模式数据库写入、部分更新vs全量替换
操作模式外部API调用、Node.js运行时
任务调度定时任务和延迟函数执行
文件存储Blob存储和元数据

Quick Reference

快速参考

Function Registration

函数注册

typescript
// Public functions (exposed to clients)
import { query, mutation, action } from "./_generated/server";

// Internal functions (only callable from other Convex functions)
import {
  internalQuery,
  internalMutation,
  internalAction,
} from "./_generated/server";
typescript
// 公开函数(对客户端暴露)
import { query, mutation, action } from "./_generated/server";

// 内部函数(仅可从其他Convex函数调用)
import {
  internalQuery,
  internalMutation,
  internalAction,
} from "./_generated/server";

Function Syntax (Always Use This)

函数语法(请始终使用此格式)

typescript
export const myFunction = query({
  args: { name: v.string() },
  returns: v.string(),
  handler: async (ctx, args) => {
    return "Hello " + args.name;
  },
});
typescript
export const myFunction = query({
  args: { name: v.string() },
  returns: v.string(),
  handler: async (ctx, args) => {
    return "Hello " + args.name;
  },
});

Common Validators

常用验证器

TypeValidatorExample
String
v.string()
"hello"
Number
v.number()
3.14
Boolean
v.boolean()
true
ID
v.id("tableName")
doc._id
Array
v.array(v.string())
["a", "b"]
Object
v.object({...})
{name: "x"}
Optional
v.optional(v.string())
undefined
Union
v.union(v.string(), v.number())
"x"
or
1
Literal
v.literal("status")
"status"
Null
v.null()
null
类型验证器示例
字符串
v.string()
"hello"
数字
v.number()
3.14
布尔值
v.boolean()
true
ID
v.id("tableName")
doc._id
数组
v.array(v.string())
["a", "b"]
对象
v.object({...})
{name: "x"}
可选值
v.optional(v.string())
undefined
联合类型
v.union(v.string(), v.number())
"x"
or
1
字面量
v.literal("status")
"status"
空值
v.null()
null

Function References

函数引用

typescript
// Public functions
import { api } from "./_generated/api";
api.example.myQuery; // convex/example.ts → myQuery

// Internal functions
import { internal } from "./_generated/api";
internal.example.myInternalMutation;
typescript
// 公开函数
import { api } from "./_generated/api";
api.example.myQuery; // convex/example.ts → myQuery

// 内部函数
import { internal } from "./_generated/api";
internal.example.myInternalMutation;

Query with Index

使用索引的查询

typescript
// Schema
messages: defineTable({...}).index("by_channel", ["channelId"])

// Query
await ctx.db
  .query("messages")
  .withIndex("by_channel", (q) => q.eq("channelId", channelId))
  .order("desc")
  .take(10);
typescript
// 模式
messages: defineTable({...}).index("by_channel", ["channelId"])

// 查询
await ctx.db
  .query("messages")
  .withIndex("by_channel", (q) => q.eq("channelId", channelId))
  .order("desc")
  .take(10);

Key Rules

核心规则

  1. Always include
    args
    and
    returns
    validators
    on all functions
  2. Use
    v.null()
    for void returns
    - never omit return validator
  3. Use
    withIndex()
    not
    filter()
    - define indexes in schema
  4. Use
    internalQuery/Mutation/Action
    for private functions
  5. Actions cannot access
    ctx.db
    - use runQuery/runMutation instead
  6. Include type annotations when calling functions in same file
  1. 所有函数必须包含
    args
    returns
    验证器
  2. 使用
    v.null()
    表示无返回值
    - 绝不要省略返回值验证器
  3. 使用
    withIndex()
    而非
    filter()
    - 在模式中定义索引
  4. 使用
    internalQuery/Mutation/Action
    处理私有函数
  5. 操作函数无法直接访问
    ctx.db
    - 请改用runQuery/runMutation
  6. 在同一文件中调用函数时添加类型注解

Full Compiled Document

完整文档

For the complete guide with all rules and detailed code examples, see:
AGENTS.md
如需包含所有规则和详细代码示例的完整指南,请查看:
AGENTS.md