Loading...
Loading...
Compare original and translation side by side
The definitive guide for building production-ready Convex applications.
构建生产级Convex应用的权威指南。
argsreturnshandler.filter().withIndex()await@typescript-eslint/no-floating-promisesinternal*ctx.dbctx.runQueryctx.runMutationnullreturns: v.null()v.id("table")v.string()@convex-dev/eslint-pluginargsreturnshandler.filter().withIndex()await@typescript-eslint/no-floating-promisesinternal*ctx.dbctx.runQueryctx.runMutationnullreturns: v.null()v.id("table")v.string()@convex-dev/eslint-plugin| Type | DB Access | External APIs | Transactional | Cached/Reactive |
|---|---|---|---|---|
| Read-only via | No | Yes | Yes |
| Read/Write via | No | Yes | No |
| Via | Yes | No | No |
| Via | Yes | No | No |
| 类型 | 数据库访问权限 | 外部API调用 | 事务支持 | 缓存/响应式 |
|---|---|---|---|---|
| 仅可读(通过 | 不支持 | 支持 | 支持 |
| 可读可写(通过 | 不支持 | 支持 | 不支持 |
| 通过 | 支持 | 不支持 | 不支持 |
| 通过 | 支持 | 不支持 | 不支持 |
import { query } from "./_generated/server";
import { v } from "convex/values";
export const getUser = 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(args.userId);
},
});import { query } from "./_generated/server";
import { v } from "convex/values";
export const getUser = 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(args.userId);
},
});import { mutation } from "./_generated/server";
import { v } from "convex/values";
export const createTask = 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, userId: args.userId,
completed: false, createdAt: Date.now(),
});
},
});import { mutation } from "./_generated/server";
import { v } from "convex/values";
export const createTask = 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, userId: args.userId,
completed: false, createdAt: Date.now(),
});
},
});"use node"; // Required for Node.js APIs
import { action } from "./_generated/server";
import { internal } from "./_generated/api";
import { v } from "convex/values";
export const processPayment = action({
args: { orderId: v.id("orders"), amount: v.number() },
returns: v.null(),
handler: async (ctx, args) => {
const order = await ctx.runQuery(internal.orders.get, { orderId: args.orderId });
const result = await fetch("https://api.stripe.com/...", { method: "POST", /* ... */ });
await ctx.runMutation(internal.orders.updateStatus, {
orderId: args.orderId, status: result.ok ? "paid" : "failed",
});
return null;
},
});"use node"; // 调用Node.js API时必填
import { action } from "./_generated/server";
import { internal } from "./_generated/api";
import { v } from "convex/values";
export const processPayment = action({
args: { orderId: v.id("orders"), amount: v.number() },
returns: v.null(),
handler: async (ctx, args) => {
const order = await ctx.runQuery(internal.orders.get, { orderId: args.orderId });
const result = await fetch("https://api.stripe.com/...", { method: "POST", /* ... */ });
await ctx.runMutation(internal.orders.updateStatus, {
orderId: args.orderId, status: result.ok ? "paid" : "failed",
});
return null;
},
});import { internalMutation, internalQuery, internalAction } from "./_generated/server";
import { internal } from "./_generated/api"; // for referencing internal functions
import { api } from "./_generated/api"; // for referencing public functionsimport { internalMutation, internalQuery, internalAction } from "./_generated/server";
import { internal } from "./_generated/api"; // 引用内部函数
import { api } from "./_generated/api"; // 引用公共函数// convex/schema.ts
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";
export default defineSchema({
users: defineTable({
name: v.string(),
email: v.string(),
role: v.union(v.literal("admin"), v.literal("member")),
settings: v.object({ theme: v.union(v.literal("light"), v.literal("dark")) }),
})
.index("by_email", ["email"])
.index("by_role", ["role"]),
messages: defineTable({
channelId: v.id("channels"),
authorId: v.id("users"),
content: v.string(),
})
.index("by_channel", ["channelId"])
.index("by_channel_and_author", ["channelId", "authorId"])
.searchIndex("search_content", { searchField: "content", filterFields: ["channelId"] }),
});by_channel_and_authorchannelIdby_channelby_channel_and_authorby_field1_and_field2.index("by_theme", ["settings.theme"])_id_creationTime// convex/schema.ts
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";
export default defineSchema({
users: defineTable({
name: v.string(),
email: v.string(),
role: v.union(v.literal("admin"), v.literal("member")),
settings: v.object({ theme: v.union(v.literal("light"), v.literal("dark")) }),
})
.index("by_email", ["email"])
.index("by_role", ["role"]),
messages: defineTable({
channelId: v.id("channels"),
authorId: v.id("users"),
content: v.string(),
})
.index("by_channel", ["channelId"])
.index("by_channel_and_author", ["channelId", "authorId"])
.searchIndex("search_content", { searchField: "content", filterFields: ["channelId"] }),
});by_channel_and_authorchannelIdby_channel_and_authorby_channelby_field1_and_field2.index("by_theme", ["settings.theme"])_id_creationTime// Read
const doc = await ctx.db.get(id); // by ID (null if not found)
const docs = await ctx.db.query("table").collect(); // all (bounded)
const first = await ctx.db.query("table").first(); // first or null
const one = await ctx.db.query("table").withIndex(...).unique(); // exactly one (throws if 0 or >1)
const top10 = await ctx.db.query("table").order("desc").take(10);
// Indexed query
const results = await ctx.db.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", channelId))
.order("desc")
.take(50);
// Write
const id = await ctx.db.insert("table", { ...fields });
await ctx.db.patch(id, { field: newValue }); // partial update
await ctx.db.replace(id, { ...allFields }); // full replace (keeps _id, _creationTime)
await ctx.db.delete(id);// 读取操作
const doc = await ctx.db.get(id); // 根据ID查询(不存在则返回null)
const docs = await ctx.db.query("table").collect(); // 查询所有数据(有数量限制)
const first = await ctx.db.query("table").first(); // 查询第一条数据(不存在则返回null)
const one = await ctx.db.query("table").withIndex(...).unique(); // 查询唯一匹配数据(无匹配或多个匹配时抛出异常)
const top10 = await ctx.db.query("table").order("desc").take(10); // 查询前10条数据(降序)
// 带索引的查询
const results = await ctx.db.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", channelId))
.order("desc")
.take(50);
// 写入操作
const id = await ctx.db.insert("table", { ...fields }); // 插入数据
await ctx.db.patch(id, { field: newValue }); // 部分更新
await ctx.db.replace(id, { ...allFields }); // 完全替换(保留_id和_creationTime)
await ctx.db.delete(id); // 删除数据v.string() v.number() v.boolean() v.null()
v.id("tableName") v.int64() v.bytes() v.any()
v.array(v.string()) v.record(v.string(), v.number())
v.object({ name: v.string(), age: v.optional(v.number()) })
v.union(v.literal("a"), v.literal("b")) // enum-like
v.optional(v.string()) // field can be omitted
v.nullable(v.string()) // shorthand for v.union(v.string(), v.null())const roleValidator = v.union(v.literal("admin"), v.literal("member"));
const profileValidator = v.object({ name: v.string(), bio: v.optional(v.string()) });import { Infer } from "convex/values";
type Role = Infer<typeof roleValidator>; // "admin" | "member"import { Doc, Id } from "./_generated/dataModel";
import { QueryCtx, MutationCtx, ActionCtx } from "./_generated/server";v.string() v.number() v.boolean() v.null()
v.id("tableName") v.int64() v.bytes() v.any()
v.array(v.string()) v.record(v.string(), v.number())
v.object({ name: v.string(), age: v.optional(v.number()) })
v.union(v.literal("a"), v.literal("b")) // 枚举风格
v.optional(v.string()) // 字段可省略
v.nullable(v.string()) // v.union(v.string(), v.null())的简写const roleValidator = v.union(v.literal("admin"), v.literal("member"));
const profileValidator = v.object({ name: v.string(), bio: v.optional(v.string()) });import { Infer } from "convex/values";
type Role = Infer<typeof roleValidator>; // "admin" | "member"import { Doc, Id } from "./_generated/dataModel";
import { QueryCtx, MutationCtx, ActionCtx } from "./_generated/server";// Reusable auth helper
export async function getCurrentUser(ctx: QueryCtx | MutationCtx) {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new ConvexError({ code: "UNAUTHORIZED", message: "Must be logged in" });
const user = await ctx.db.query("users")
.withIndex("by_token", (q) => q.eq("tokenIdentifier", identity.tokenIdentifier))
.unique();
if (!user) throw new ConvexError({ code: "USER_NOT_FOUND", message: "User not found" });
return user;
}ctx.authsetTeamNametransferOwnershipupdateTeaminternalMutation// 可复用的身份验证工具函数
export async function getCurrentUser(ctx: QueryCtx | MutationCtx) {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new ConvexError({ code: "UNAUTHORIZED", message: "请先登录" });
const user = await ctx.db.query("users")
.withIndex("by_token", (q) => q.eq("tokenIdentifier", identity.tokenIdentifier))
.unique();
if (!user) throw new ConvexError({ code: "USER_NOT_FOUND", message: "用户不存在" });
return user;
}ctx.authsetTeamNametransferOwnershipupdateTeaminternalMutationimport { ConvexError } from "convex/values";
// Throw structured errors
throw new ConvexError({ code: "NOT_FOUND", message: "Task not found" });
// Client catches
try { await createUser({ email }); }
catch (error) {
if (error instanceof ConvexError) { /* error.data.code, error.data.message */ }
}ConvexErrorimport { ConvexError } from "convex/values";
// 抛出结构化错误
throw new ConvexError({ code: "NOT_FOUND", message: "任务不存在" });
// 客户端捕获错误
try { await createUser({ email }); }
catch (error) {
if (error instanceof ConvexError) { /* error.data.code, error.data.message */ }
}ConvexErrorconvex/
├── schema.ts # Schema + indexes
├── auth.ts # getCurrentUser, requireTeamMember helpers
├── users.ts # Public user API (thin wrappers)
├── teams.ts # Public team API
├── model/
│ ├── users.ts # User business logic (pure TS functions)
│ └── teams.ts # Team business logic
├── http.ts # HTTP actions (webhooks, APIs)
├── crons.ts # Cron jobs
└── convex.config.ts # Component registrationmodel/ctx.runActionctx.runActionconvex/
├── schema.ts # Schema与索引
├── auth.ts # getCurrentUser、权限校验等工具函数
├── users.ts # 公共用户API(轻量封装)
├── teams.ts # 公共团队API
├── model/
│ ├── users.ts # 用户业务逻辑(纯TypeScript函数)
│ └── teams.ts # 团队业务逻辑
├── http.ts # HTTP动作(Webhook、外部API)
├── crons.ts # Cron任务
└── convex.config.ts # 组件注册model/ctx.runActionctx.runAction