convex-actions-general
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseConvex Actions and General Guidelines Skill
Convex Actions及通用开发指南
This skill provides comprehensive guidance for Convex actions, HTTP endpoints, validators, schema design, file storage, environment variables, scheduling, and TypeScript best practices.
本技能为Convex actions、HTTP端点、验证器、Schema设计、文件存储、环境变量、任务调度以及TypeScript最佳实践提供全面指导。
When to Use This Skill
何时使用本技能
Use this skill when:
- Implementing action functions for external API calls and long-running tasks
- Creating HTTP endpoints for webhooks or public APIs
- Defining validators for function arguments and database schemas
- Designing database schemas with tables, indexes, and search capabilities
- Setting up environment variables for secrets and configuration
- Implementing cron jobs and scheduled tasks
- Working with file storage for uploads and downloads
- Using Convex-specific TypeScript patterns and types
- Understanding Convex limits and performance constraints
在以下场景中使用本技能:
- 实现用于外部API调用和长时间运行任务的action函数
- 为webhook或公共API创建HTTP端点
- 为函数参数和数据库Schema定义验证器
- 设计包含表、索引和搜索功能的数据库Schema
- 为密钥和配置设置环境变量
- 实现定时任务和计划任务
- 处理用于上传和下载的文件存储
- 使用Convex专属的TypeScript模式和类型
- 了解Convex的限制和性能约束
Skill Resources
技能资源
This skill includes comprehensive reference documentation in that covers:
references/actions-and-general.md本技能包含位于的全面参考文档,涵盖以下内容:
references/actions-and-general.mdActions and HTTP
Actions与HTTP
- Actions: Defining actions with for Node.js modules
"use node"- V8 vs Node runtime differences
- Action limitations (10-minute timeout, no database access)
- Calling external APIs and services
- HTTP Endpoints: Setting up with httpRouter
convex/http.ts- Path registration and exact matching
- Request/response handling
- Method definitions (POST, GET, etc.)
- Actions:使用定义用于Node.js模块的actions
"use node"- V8与Node运行时的差异
- Action限制(10分钟超时,无数据库访问权限)
- 调用外部API和服务
- HTTP端点:使用httpRouter设置
convex/http.ts- 路径注册与精确匹配
- 请求/响应处理
- 方法定义(POST、GET等)
Validators and Types
验证器与类型
- Complete validator reference for all Convex types
- Common validators: ,
v.object(),v.array(),v.string(),v.number(),v.id(),v.boolean()v.null() - Discriminated union types with and
v.union()v.literal() - ASCII field name requirements for objects
- Size and element count limits
- 所有Convex类型的完整验证器参考
- 常用验证器:、
v.object()、v.array()、v.string()、v.number()、v.id()、v.boolean()v.null() - 使用和
v.union()实现区分联合类型v.literal() - 对象的ASCII字段名要求
- 大小和元素数量限制
Function Development
函数开发
- New function syntax for all function types
- Function registration patterns (,
query,mutation,action,internalQuery,internalMutation)internalAction - Function calling patterns across runtimes
- Function references via and
apiobjectsinternal - File-based routing conventions
- 所有函数类型的新函数语法
- 函数注册模式(、
query、mutation、action、internalQuery、internalMutation)internalAction - 跨运行时的函数调用模式
- 通过和
api对象引用函数internal - 基于文件的路由约定
API Design
API设计
- Organizing public and private functions
- Thoughtful file structure within directory
convex/ - Public vs. internal function visibility
- API surface consistency
- 组织公共和私有函数
- 目录内的合理文件结构
convex/ - 公共与内部函数的可见性
- API表面的一致性
Database and Schema
数据库与Schema
- Schema Definition: structure
convex/schema.ts- System fields (,
_id)_creationTime - Table definitions with validators
- System fields (
- Indexes: Creating efficient indexes
- Built-in indexes (by_id, by_creation_time)
- Custom index naming and field ordering
- Multiple field indexes for complex queries
- Full Text Search: Search index definitions
- Search fields and filter fields
- Nested field paths with dot notation
- Schema定义:的结构
convex/schema.ts- 系统字段(、
_id)_creationTime - 带验证器的表定义
- 系统字段(
- 索引:创建高效索引
- 内置索引(by_id、by_creation_time)
- 自定义索引命名和字段排序
- 用于复杂查询的多字段索引
- 全文搜索:搜索索引定义
- 搜索字段和过滤字段
- 使用点符号的嵌套字段路径
Environment and Configuration
环境与配置
- Environment Variables: Using
process.env- Storing secrets (API keys, credentials)
- Per-deployment configuration
- Access from any function type
- Scheduling:
- Crons: Using and
crons.interval()crons.cron() - Scheduler: Using from mutations/actions
ctx.scheduler.runAfter() - Auth state propagation (doesn't propagate to scheduled jobs)
- Timing constraints and best practices
- Crons: Using
- 环境变量:使用
process.env- 存储密钥(API密钥、凭证)
- 按部署配置
- 可从任何函数类型访问
- 任务调度:
- 定时任务:使用和
crons.interval()crons.cron() - 调度器:在mutations/actions中使用
ctx.scheduler.runAfter() - 认证状态传播(不会传播到计划任务)
- 时间约束与最佳实践
- 定时任务:使用
File Storage
文件存储
- Upload URL generation with
ctx.storage.generateUploadUrl() - Signed URL retrieval with
ctx.storage.getUrl() - File metadata from system table
_storage - Blob conversion for storage operations
- Complete example: image upload in chat application
- 使用生成上传URL
ctx.storage.generateUploadUrl() - 使用获取签名URL
ctx.storage.getUrl() - 来自系统表的文件元数据
_storage - 用于存储操作的Blob转换
- 完整示例:聊天应用中的图片上传
Limits and Performance
限制与性能
- Function arguments and return values: 8 MiB maximum
- Database operations: 8192 document writes per mutation, 16384 reads per query
- Execution timeouts: 1 second for queries/mutations, 10 minutes for actions
- Array element limits: 8192 maximum
- Object/Record field limits: 1024 maximum
- Nesting depth: 16 maximum
- Record size: 1 MiB maximum
- HTTP streaming: 20 MiB maximum output
- 函数参数和返回值:最大8 MiB
- 数据库操作:每个mutation最多8192次文档写入,每个query最多16384次读取
- 执行超时:查询/变更为1秒,actions为10分钟
- 数组元素限制:最多8192个
- 对象/记录字段限制:最多1024个
- 嵌套深度:最多16层
- 记录大小:最大1 MiB
- HTTP流式输出:最大20 MiB
TypeScript
TypeScript
- types for strict document IDs
Id<'tableName'> - types for document type safety
Doc<'tableName'> - with proper typing
Record<KeyType, ValueType> - for discriminated unions
as const - Type annotations for same-file function calls
- for Node.js modules
@types/node
- 类型用于严格的文档ID
Id<'tableName'> - 类型用于文档类型安全
Doc<'tableName'> - 正确类型化的
Record<KeyType, ValueType> - 使用实现区分联合类型
as const - 同文件函数调用的类型注解
- 用于Node.js模块
@types/node
How to Use This Skill
如何使用本技能
- Read the reference documentation at for comprehensive patterns
references/actions-and-general.md - Follow the syntax for defining actions with proper Node.js module handling
- Use validators correctly for all function arguments and schema fields
- Design schemas with appropriate indexes for your access patterns
- Set up environment variables for secrets and configuration
- Implement scheduling for background tasks using crons or the scheduler
- Handle file storage with proper URL generation and metadata lookup
- Understand limits and design applications to respect them
- Use TypeScript strictly with types and proper generics
Id
- 阅读参考文档:查看获取全面的开发模式
references/actions-and-general.md - 遵循语法规范:定义actions时正确处理Node.js模块
- 正确使用验证器:为所有函数参数和Schema字段添加验证器
- 设计合理的Schema:根据你的访问模式配置适当的索引
- 设置环境变量:用于存储密钥和配置信息
- 实现任务调度:使用定时任务或调度器处理后台任务
- 处理文件存储:正确生成URL并查询元数据
- 了解限制条件:设计应用时需遵守Convex的各项限制
- 严格使用TypeScript:使用类型和正确的泛型
Id
Key General Guidelines
关键通用指南
- ALWAYS use argument validators for all functions (queries, mutations, actions)
- Do NOT store file URLs in the database; store file IDs instead
- Remapping non-ASCII characters (emoji) to ASCII codes before storing in objects
- Auth state does NOT propagate to scheduled jobs; use internal functions
- Scheduled functions should not run more than once every 10 seconds
- Never call actions from other actions unless crossing runtimes (V8 to Node)
- Objects in Convex must have ASCII-only field names
- Be strict with TypeScript types, especially for document IDs
- 始终为所有函数(查询、变更、actions)使用参数验证器
- 不要在数据库中存储文件URL;应存储文件ID
- 在存储到对象前,将非ASCII字符(如表情符号)映射为ASCII编码
- 认证状态不会传播到计划任务;请使用内部函数
- 计划任务的运行频率不应超过每10秒一次
- 除非跨运行时(V8到Node),否则不要从其他actions中调用actions
- Convex中的对象必须仅包含ASCII字段名
- 严格使用TypeScript类型,尤其是文档ID
Example: Complete Action with HTTP Endpoint
示例:带HTTP端点的完整Action
ts
// convex/ai.ts
"use node";
import { action } from "./_generated/server";
import { v } from "convex/values";
import { internal } from "./_generated/api";
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
export const generateResponse = action({
args: {
channelId: v.id("channels"),
},
handler: async (ctx, args) => {
// Actions can't access ctx.db, but can call mutations
const context = await ctx.runQuery(internal.functions.loadContext, {
channelId: args.channelId,
});
const response = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: context,
});
const content = response.choices[0].message.content;
if (!content) throw new Error("No content in response");
await ctx.runMutation(internal.functions.writeAgentResponse, {
channelId: args.channelId,
content,
});
return null;
},
});ts
// convex/ai.ts
"use node";
import { action } from "./_generated/server";
import { v } from "convex/values";
import { internal } from "./_generated/api";
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
export const generateResponse = action({
args: {
channelId: v.id("channels"),
},
handler: async (ctx, args) => {
// Actions无法访问ctx.db,但可以调用mutations
const context = await ctx.runQuery(internal.functions.loadContext, {
channelId: args.channelId,
});
const response = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: context,
});
const content = response.choices[0].message.content;
if (!content) throw new Error("No content in response");
await ctx.runMutation(internal.functions.writeAgentResponse, {
channelId: args.channelId,
content,
});
return null;
},
});Example: HTTP Endpoint
示例:HTTP端点
ts
// convex/http.ts
import { httpRouter } from "convex/server";
import { httpAction } from "./_generated/server";
const http = httpRouter();
http.route({
path: "/webhook",
method: "POST",
handler: httpAction(async (ctx, req) => {
const body = await req.json();
// Process webhook payload
return new Response(JSON.stringify({ success: true }), { status: 200 });
}),
});
export default http;For more detailed information and additional patterns, refer to the complete reference documentation.
ts
// convex/http.ts
import { httpRouter } from "convex/server";
import { httpAction } from "./_generated/server";
const http = httpRouter();
http.route({
path: "/webhook",
method: "POST",
handler: httpAction(async (ctx, req) => {
const body = await req.json();
// 处理webhook负载
return new Response(JSON.stringify({ success: true }), { status: 200 });
}),
});
export default http;如需更详细的信息和其他开发模式,请参考完整的参考文档。