重要前提
安装AI Skills的关键前提是:必须科学上网,且开启TUN模式,这一点至关重要,直接决定安装能否顺利完成,在此郑重提醒三遍:科学上网,科学上网,科学上网。查看完整安装教程 →
convex-anti-patterns by fluid-tools/claude-skills
npx skills add https://github.com/fluid-tools/claude-skills --skill convex-anti-patterns此技能记录了在 Convex 开发中需要避免的关键错误以及代理必须遵循的规则。这里的每个模式都曾导致实际的生产问题。
any 类型关键规则: 此代码库已启用 @typescript-eslint/no-explicit-any。使用 any 将导致构建失败。
❌ 错误:
function handleData(data: any) { ... }
const items: any[] = [];
args: { data: v.any() } // 也要避免!
✅ 正确:
function handleData(data: Doc<"items">) { ... }
const items: Doc<"items">[] = [];
args: { data: v.object({ field: v.string() }) }
在以下情况下使用此技能:
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
变更操作必须是确定性的。外部调用会破坏这一保证。
❌ 错误:
export const createOrder = mutation({
args: { productId: v.string() },
returns: v.null(),
handler: async (ctx, args) => {
// ❌ 变更操作不能进行外部 HTTP 调用!
const price = await fetch(
`https://api.stripe.com/prices/${args.productId}`
);
await ctx.db.insert("orders", {
productId: args.productId,
price: await price.json(),
});
return null;
},
});
✅ 正确:
// 变更操作创建记录,安排动作进行外部调用
export const createOrder = mutation({
args: { productId: v.string() },
returns: v.id("orders"),
handler: async (ctx, args) => {
const orderId = await ctx.db.insert("orders", {
productId: args.productId,
status: "pending",
});
await ctx.scheduler.runAfter(0, internal.orders.fetchPrice, { orderId });
return orderId;
},
});
// 动作处理外部 API 调用
export const fetchPrice = internalAction({
args: { orderId: v.id("orders") },
returns: v.null(),
handler: async (ctx, args) => {
const order = await ctx.runQuery(internal.orders.getById, {
orderId: args.orderId,
});
if (!order) return null;
const response = await fetch(
`https://api.stripe.com/prices/${order.productId}`
);
const priceData = await response.json();
await ctx.runMutation(internal.orders.updatePrice, {
orderId: args.orderId,
price: priceData.unit_amount,
});
return null;
},
});
动作没有数据库访问权限。这是 TypeScript 错误的常见来源。
❌ 错误:
export const processData = action({
args: { id: v.id("items") },
returns: v.null(),
handler: async (ctx, args) => {
// ❌ 动作没有 ctx.db!
const item = await ctx.db.get(args.id); // TypeScript 错误!
return null;
},
});
✅ 正确:
export const processData = action({
args: { id: v.id("items") },
returns: v.null(),
handler: async (ctx, args) => {
// ✅ 使用 ctx.runQuery 进行读取
const item = await ctx.runQuery(internal.items.getById, { id: args.id });
// 使用外部 API 进行处理...
const result = await fetch("https://api.example.com/process", {
method: "POST",
body: JSON.stringify(item),
});
// ✅ 使用 ctx.runMutation 进行写入
await ctx.runMutation(internal.items.updateResult, {
id: args.id,
result: await result.json(),
});
return null;
},
});
每个函数都必须有显式的 returns 验证器。
❌ 错误:
export const doSomething = mutation({
args: { data: v.string() },
// ❌ 缺少 returns!
handler: async (ctx, args) => {
await ctx.db.insert("items", { data: args.data });
// 隐式返回 undefined
},
});
✅ 正确:
export const doSomething = mutation({
args: { data: v.string() },
returns: v.null(), // ✅ 显式的返回验证器
handler: async (ctx, args) => {
await ctx.db.insert("items", { data: args.data });
return null; // ✅ 显式的返回值
},
});
.filter() 会扫描整个表。始终使用索引。
❌ 错误:
export const getActiveUsers = query({
args: {},
returns: v.array(v.object({ _id: v.id("users"), name: v.string() })),
handler: async (ctx) => {
// ❌ 全表扫描!
return await ctx.db
.query("users")
.filter((q) => q.eq(q.field("status"), "active"))
.collect();
},
});
✅ 正确:
// 模式:.index("by_status", ["status"])
export const getActiveUsers = query({
args: {},
returns: v.array(v.object({ _id: v.id("users"), name: v.string() })),
handler: async (ctx) => {
// ✅ 使用索引
return await ctx.db
.query("users")
.withIndex("by_status", (q) => q.eq("status", "active"))
.collect();
},
});
切勿在可能很大的表上进行无限制的收集。
❌ 错误:
export const getAllMessages = query({
args: { channelId: v.id("channels") },
returns: v.array(v.object({ content: v.string() })),
handler: async (ctx, args) => {
// ❌ 可能返回数百万条记录!
return await ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
.collect();
},
});
✅ 正确:
export const getRecentMessages = query({
args: { channelId: v.id("channels") },
returns: v.array(v.object({ content: v.string() })),
handler: async (ctx, args) => {
// ✅ 使用 take() 进行限制
return await ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
.order("desc")
.take(50);
},
});
仅仅为了计数而收集是浪费的。
❌ 错误:
export const getMessageCount = query({
args: { channelId: v.id("channels") },
returns: v.number(),
handler: async (ctx, args) => {
// ❌ 加载所有消息仅仅是为了计数!
const messages = await ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
.collect();
return messages.length;
},
});
✅ 正确:
// 选项 1:使用 "99+" 显示的有界计数
export const getMessageCount = query({
args: { channelId: v.id("channels") },
returns: v.string(),
handler: async (ctx, args) => {
const messages = await ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
.take(100);
return messages.length === 100 ? "99+" : String(messages.length);
},
});
// 选项 2:非规范化计数器(适用于高流量场景)
// 在 channels 表中维护 messageCount 字段
export const getMessageCount = query({
args: { channelId: v.id("channels") },
returns: v.number(),
handler: async (ctx, args) => {
const channel = await ctx.db.get(args.channelId);
return channel?.messageCount ?? 0;
},
});
逐个加载相关文档。
❌ 错误:
export const getPostsWithAuthors = query({
args: {},
returns: v.array(
v.object({
post: v.object({ title: v.string() }),
author: v.object({ name: v.string() }),
})
),
handler: async (ctx) => {
const posts = await ctx.db.query("posts").take(10);
// ❌ N 次额外的查询!
const postsWithAuthors = await Promise.all(
posts.map(async (post) => ({
post: { title: post.title },
author: await ctx.db
.get(post.authorId)
.then((a) => ({ name: a!.name })),
}))
);
return postsWithAuthors;
},
});
✅ 正确:
import { getAll } from "convex-helpers/server/relationships";
export const getPostsWithAuthors = query({
args: {},
returns: v.array(
v.object({
post: v.object({ title: v.string() }),
author: v.union(v.object({ name: v.string() }), v.null()),
})
),
handler: async (ctx) => {
const posts = await ctx.db.query("posts").take(10);
// ✅ 批量获取所有作者
const authorIds = [...new Set(posts.map((p) => p.authorId))];
const authors = await getAll(ctx.db, authorIds);
const authorMap = new Map(
authors
.filter((a): a is NonNullable<typeof a> => a !== null)
.map((a) => [a._id, a])
);
return posts.map((post) => ({
post: { title: post.title },
author: authorMap.get(post.authorId)
? { name: authorMap.get(post.authorId)!.name }
: null,
}));
},
});
单文档更新在高负载下会导致 OCC 冲突。
❌ 错误:
export const incrementPageViews = mutation({
args: {},
returns: v.null(),
handler: async (ctx) => {
// ❌ 每个请求都写入同一个文档!
const stats = await ctx.db.query("globalStats").unique();
await ctx.db.patch(stats!._id, { views: stats!.views + 1 });
return null;
},
});
✅ 正确:
// 选项 1:分片
export const incrementPageViews = mutation({
args: {},
returns: v.null(),
handler: async (ctx) => {
// ✅ 写入随机分片
const shardId = Math.floor(Math.random() * 10);
await ctx.db.insert("viewShards", { shardId, delta: 1 });
return null;
},
});
// 通过聚合分片进行读取
export const getPageViews = query({
args: {},
returns: v.number(),
handler: async (ctx) => {
const shards = await ctx.db.query("viewShards").collect();
return shards.reduce((sum, s) => sum + s.delta, 0);
},
});
// 选项 2:使用 Workpool 进行序列化
import { Workpool } from "@convex-dev/workpool";
const counterPool = new Workpool(components.workpool, { maxParallelism: 1 });
export const incrementPageViews = mutation({
args: {},
returns: v.null(),
handler: async (ctx) => {
await counterPool.enqueueMutation(ctx, internal.stats.doIncrement, {});
return null;
},
});
❌ 错误:
export default defineSchema({
counters: defineTable({
value: v.bigint(), // ❌ 已弃用!
}),
});
✅ 正确:
export default defineSchema({
counters: defineTable({
value: v.int64(), // ✅ 使用 v.int64()
}),
});
❌ 错误:
export const getUser = query({
args: { userId: v.id("users") },
returns: v.object({
// ❌ 缺少 _id 和 _creationTime!
name: v.string(),
email: v.string(),
}),
handler: async (ctx, args) => {
return await ctx.db.get(args.userId); // 返回包含系统字段的完整文档
},
});
✅ 正确:
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);
},
});
❌ 错误:
// ❌ 任何客户端都可以调用此函数!
export const deleteUserData = mutation({
args: { userId: v.id("users") },
returns: v.null(),
handler: async (ctx, args) => {
// 公开暴露的危险操作
await ctx.db.delete(args.userId);
return null;
},
});
✅ 正确:
// 内部变更操作 - 客户端不可调用
export const deleteUserData = internalMutation({
args: { userId: v.id("users") },
returns: v.null(),
handler: async (ctx, args) => {
await ctx.db.delete(args.userId);
return null;
},
});
// 带有身份验证检查的公共变更操作
export const requestAccountDeletion = mutation({
args: {},
returns: v.null(),
handler: async (ctx) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new Error("Unauthorized");
const user = await ctx.db
.query("users")
.withIndex("by_token", (q) =>
q.eq("tokenIdentifier", identity.tokenIdentifier)
)
.unique();
if (!user) throw new Error("User not found");
// 安排内部变更操作
await ctx.scheduler.runAfter(0, internal.users.deleteUserData, {
userId: user._id,
});
return null;
},
});
❌ 错误:
export const transferFunds = action({
args: { from: v.id("accounts"), to: v.id("accounts"), amount: v.number() },
returns: v.null(),
handler: async (ctx, args) => {
// ❌ 这些是独立的事务 - 可能导致不一致状态!
await ctx.runMutation(internal.accounts.debit, {
accountId: args.from,
amount: args.amount,
});
// 如果此操作失败,钱已被扣除但未存入!
await ctx.runMutation(internal.accounts.credit, {
accountId: args.to,
amount: args.amount,
});
return null;
},
});
✅ 正确:
// 单个原子变更操作
export const transferFunds = mutation({
args: { from: v.id("accounts"), to: v.id("accounts"), amount: v.number() },
returns: v.null(),
handler: async (ctx, args) => {
// ✅ 全部在一个事务中 - 要么全部成功,要么全部失败
const fromAccount = await ctx.db.get(args.from);
const toAccount = await ctx.db.get(args.to);
if (!fromAccount || !toAccount) throw new Error("Account not found");
if (fromAccount.balance < args.amount)
throw new Error("Insufficient funds");
await ctx.db.patch(args.from, {
balance: fromAccount.balance - args.amount,
});
await ctx.db.patch(args.to, { balance: toAccount.balance + args.amount });
return null;
},
});
❌ 错误:
export default defineSchema({
messages: defineTable({
channelId: v.id("channels"),
authorId: v.id("users"),
content: v.string(),
})
.index("by_channel", ["channelId"]) // ❌ 冗余!
.index("by_channel_author", ["channelId", "authorId"]),
});
✅ 正确:
export default defineSchema({
messages: defineTable({
channelId: v.id("channels"),
authorId: v.id("users"),
content: v.string(),
})
// ✅ 单个复合索引服务于两种查询模式
.index("by_channel_author", ["channelId", "authorId"]),
});
// 对于仅按频道查询的情况,使用前缀匹配:
// .withIndex("by_channel_author", (q) => q.eq("channelId", id))
❌ 错误:
export const getMessage = query({
args: { messageId: v.string() }, // ❌ 应该是 v.id()
returns: v.null(),
handler: async (ctx, args) => {
// 类型错误或运行时错误
return await ctx.db.get(args.messageId as Id<"messages">);
},
});
✅ 正确:
export const getMessage = query({
args: { messageId: v.id("messages") }, // ✅ 正确的 ID 类型
returns: v.union(
v.object({
_id: v.id("messages"),
_creationTime: v.number(),
content: v.string(),
}),
v.null()
),
handler: async (ctx, args) => {
return await ctx.db.get(args.messageId);
},
});
❌ 错误:
export const processWithRetry = internalAction({
args: { jobId: v.id("jobs"), attempt: v.number() },
returns: v.null(),
handler: async (ctx, args) => {
try {
// 处理...
} catch (error) {
if (args.attempt < 5) {
// ❌ 固定延迟会导致惊群效应!
await ctx.scheduler.runAfter(5000, internal.jobs.processWithRetry, {
jobId: args.jobId,
attempt: args.attempt + 1,
});
}
}
return null;
},
});
✅ 正确:
export const processWithRetry = internalAction({
args: { jobId: v.id("jobs"), attempt: v.number() },
returns: v.null(),
handler: async (ctx, args) => {
try {
// 处理...
} catch (error) {
if (args.attempt < 5) {
// ✅ 指数退避 + 抖动
const baseDelay = Math.pow(2, args.attempt) * 1000;
const jitter = Math.random() * 1000;
await ctx.scheduler.runAfter(
baseDelay + jitter,
internal.jobs.processWithRetry,
{
jobId: args.jobId,
attempt: args.attempt + 1,
}
);
}
}
return null;
},
});
returns 验证器 在每个函数上.filter()take(n) 用于可能很大的查询v.id("table") 用于文档 ID 参数internalMutation/internalAction 用于敏感操作fetch() 在变更操作中ctx.db 在动作中.filter() 在数据库查询上.collect() 在大表上不加限制v.bigint()(已弃用,使用 v.int64())any 类型(ESLint 规则已强制执行)提交 Convex 代码前,请验证:
returns 验证器.filter()).collect() 调用都使用 .take(n) 进行限制v.id("tableName")ctx.runQuery/ctx.runMutation 进行数据库访问any 类型每周安装次数
62
仓库
GitHub 星标数
16
首次出现时间
2026年1月20日
安全审计
安装于
opencode54
claude-code52
codex51
gemini-cli51
github-copilot46
cursor44
This skill documents critical mistakes to avoid in Convex development and rules that agents must follow. Every pattern here has caused real production issues.
any TypeCRITICAL RULE: This codebase has @typescript-eslint/no-explicit-any enabled. Using any will cause build failures.
❌ WRONG:
function handleData(data: any) { ... }
const items: any[] = [];
args: { data: v.any() } // Also avoid!
✅ CORRECT:
function handleData(data: Doc<"items">) { ... }
const items: Doc<"items">[] = [];
args: { data: v.object({ field: v.string() }) }
Use this skill when:
Mutations must be deterministic. External calls break this guarantee.
❌ WRONG:
export const createOrder = mutation({
args: { productId: v.string() },
returns: v.null(),
handler: async (ctx, args) => {
// ❌ Mutations cannot make external HTTP calls!
const price = await fetch(
`https://api.stripe.com/prices/${args.productId}`
);
await ctx.db.insert("orders", {
productId: args.productId,
price: await price.json(),
});
return null;
},
});
✅ CORRECT:
// Mutation creates record, schedules action for external call
export const createOrder = mutation({
args: { productId: v.string() },
returns: v.id("orders"),
handler: async (ctx, args) => {
const orderId = await ctx.db.insert("orders", {
productId: args.productId,
status: "pending",
});
await ctx.scheduler.runAfter(0, internal.orders.fetchPrice, { orderId });
return orderId;
},
});
// Action handles external API call
export const fetchPrice = internalAction({
args: { orderId: v.id("orders") },
returns: v.null(),
handler: async (ctx, args) => {
const order = await ctx.runQuery(internal.orders.getById, {
orderId: args.orderId,
});
if (!order) return null;
const response = await fetch(
`https://api.stripe.com/prices/${order.productId}`
);
const priceData = await response.json();
await ctx.runMutation(internal.orders.updatePrice, {
orderId: args.orderId,
price: priceData.unit_amount,
});
return null;
},
});
Actions don't have database access. This is a common source of TypeScript errors.
❌ WRONG:
export const processData = action({
args: { id: v.id("items") },
returns: v.null(),
handler: async (ctx, args) => {
// ❌ Actions don't have ctx.db!
const item = await ctx.db.get(args.id); // TypeScript Error!
return null;
},
});
✅ CORRECT:
export const processData = action({
args: { id: v.id("items") },
returns: v.null(),
handler: async (ctx, args) => {
// ✅ Use ctx.runQuery to read
const item = await ctx.runQuery(internal.items.getById, { id: args.id });
// Process with external APIs...
const result = await fetch("https://api.example.com/process", {
method: "POST",
body: JSON.stringify(item),
});
// ✅ Use ctx.runMutation to write
await ctx.runMutation(internal.items.updateResult, {
id: args.id,
result: await result.json(),
});
return null;
},
});
Every function must have an explicit returns validator.
❌ WRONG:
export const doSomething = mutation({
args: { data: v.string() },
// ❌ Missing returns!
handler: async (ctx, args) => {
await ctx.db.insert("items", { data: args.data });
// Implicitly returns undefined
},
});
✅ CORRECT:
export const doSomething = mutation({
args: { data: v.string() },
returns: v.null(), // ✅ Explicit returns validator
handler: async (ctx, args) => {
await ctx.db.insert("items", { data: args.data });
return null; // ✅ Explicit return value
},
});
.filter() scans the entire table. Always use indexes.
❌ WRONG:
export const getActiveUsers = query({
args: {},
returns: v.array(v.object({ _id: v.id("users"), name: v.string() })),
handler: async (ctx) => {
// ❌ Full table scan!
return await ctx.db
.query("users")
.filter((q) => q.eq(q.field("status"), "active"))
.collect();
},
});
✅ CORRECT:
// Schema: .index("by_status", ["status"])
export const getActiveUsers = query({
args: {},
returns: v.array(v.object({ _id: v.id("users"), name: v.string() })),
handler: async (ctx) => {
// ✅ Uses index
return await ctx.db
.query("users")
.withIndex("by_status", (q) => q.eq("status", "active"))
.collect();
},
});
Never collect without limits on potentially large tables.
❌ WRONG:
export const getAllMessages = query({
args: { channelId: v.id("channels") },
returns: v.array(v.object({ content: v.string() })),
handler: async (ctx, args) => {
// ❌ Could return millions of records!
return await ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
.collect();
},
});
✅ CORRECT:
export const getRecentMessages = query({
args: { channelId: v.id("channels") },
returns: v.array(v.object({ content: v.string() })),
handler: async (ctx, args) => {
// ✅ Bounded with take()
return await ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
.order("desc")
.take(50);
},
});
Collecting just to count is wasteful.
❌ WRONG:
export const getMessageCount = query({
args: { channelId: v.id("channels") },
returns: v.number(),
handler: async (ctx, args) => {
// ❌ Loads all messages just to count!
const messages = await ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
.collect();
return messages.length;
},
});
✅ CORRECT:
// Option 1: Bounded count with "99+" display
export const getMessageCount = query({
args: { channelId: v.id("channels") },
returns: v.string(),
handler: async (ctx, args) => {
const messages = await ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
.take(100);
return messages.length === 100 ? "99+" : String(messages.length);
},
});
// Option 2: Denormalized counter (best for high traffic)
// Maintain messageCount field in channels table
export const getMessageCount = query({
args: { channelId: v.id("channels") },
returns: v.number(),
handler: async (ctx, args) => {
const channel = await ctx.db.get(args.channelId);
return channel?.messageCount ?? 0;
},
});
Loading related documents one by one.
❌ WRONG:
export const getPostsWithAuthors = query({
args: {},
returns: v.array(
v.object({
post: v.object({ title: v.string() }),
author: v.object({ name: v.string() }),
})
),
handler: async (ctx) => {
const posts = await ctx.db.query("posts").take(10);
// ❌ N additional queries!
const postsWithAuthors = await Promise.all(
posts.map(async (post) => ({
post: { title: post.title },
author: await ctx.db
.get(post.authorId)
.then((a) => ({ name: a!.name })),
}))
);
return postsWithAuthors;
},
});
✅ CORRECT:
import { getAll } from "convex-helpers/server/relationships";
export const getPostsWithAuthors = query({
args: {},
returns: v.array(
v.object({
post: v.object({ title: v.string() }),
author: v.union(v.object({ name: v.string() }), v.null()),
})
),
handler: async (ctx) => {
const posts = await ctx.db.query("posts").take(10);
// ✅ Batch fetch all authors
const authorIds = [...new Set(posts.map((p) => p.authorId))];
const authors = await getAll(ctx.db, authorIds);
const authorMap = new Map(
authors
.filter((a): a is NonNullable<typeof a> => a !== null)
.map((a) => [a._id, a])
);
return posts.map((post) => ({
post: { title: post.title },
author: authorMap.get(post.authorId)
? { name: authorMap.get(post.authorId)!.name }
: null,
}));
},
});
Single document updates cause OCC conflicts under load.
❌ WRONG:
export const incrementPageViews = mutation({
args: {},
returns: v.null(),
handler: async (ctx) => {
// ❌ Every request writes to same document!
const stats = await ctx.db.query("globalStats").unique();
await ctx.db.patch(stats!._id, { views: stats!.views + 1 });
return null;
},
});
✅ CORRECT:
// Option 1: Sharding
export const incrementPageViews = mutation({
args: {},
returns: v.null(),
handler: async (ctx) => {
// ✅ Write to random shard
const shardId = Math.floor(Math.random() * 10);
await ctx.db.insert("viewShards", { shardId, delta: 1 });
return null;
},
});
// Read by aggregating shards
export const getPageViews = query({
args: {},
returns: v.number(),
handler: async (ctx) => {
const shards = await ctx.db.query("viewShards").collect();
return shards.reduce((sum, s) => sum + s.delta, 0);
},
});
// Option 2: Use Workpool to serialize
import { Workpool } from "@convex-dev/workpool";
const counterPool = new Workpool(components.workpool, { maxParallelism: 1 });
export const incrementPageViews = mutation({
args: {},
returns: v.null(),
handler: async (ctx) => {
await counterPool.enqueueMutation(ctx, internal.stats.doIncrement, {});
return null;
},
});
❌ WRONG:
export default defineSchema({
counters: defineTable({
value: v.bigint(), // ❌ Deprecated!
}),
});
✅ CORRECT:
export default defineSchema({
counters: defineTable({
value: v.int64(), // ✅ Use v.int64()
}),
});
❌ WRONG:
export const getUser = query({
args: { userId: v.id("users") },
returns: v.object({
// ❌ Missing _id and _creationTime!
name: v.string(),
email: v.string(),
}),
handler: async (ctx, args) => {
return await ctx.db.get(args.userId); // Returns full doc including system fields
},
});
✅ CORRECT:
export const getUser = query({
args: { userId: v.id("users") },
returns: v.union(
v.object({
_id: v.id("users"), // ✅ Include system fields
_creationTime: v.number(),
name: v.string(),
email: v.string(),
}),
v.null()
),
handler: async (ctx, args) => {
return await ctx.db.get(args.userId);
},
});
❌ WRONG:
// ❌ This is callable by any client!
export const deleteUserData = mutation({
args: { userId: v.id("users") },
returns: v.null(),
handler: async (ctx, args) => {
// Dangerous operation exposed publicly
await ctx.db.delete(args.userId);
return null;
},
});
✅ CORRECT:
// Internal mutation - not callable by clients
export const deleteUserData = internalMutation({
args: { userId: v.id("users") },
returns: v.null(),
handler: async (ctx, args) => {
await ctx.db.delete(args.userId);
return null;
},
});
// Public mutation with auth check
export const requestAccountDeletion = mutation({
args: {},
returns: v.null(),
handler: async (ctx) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new Error("Unauthorized");
const user = await ctx.db
.query("users")
.withIndex("by_token", (q) =>
q.eq("tokenIdentifier", identity.tokenIdentifier)
)
.unique();
if (!user) throw new Error("User not found");
// Schedule internal mutation
await ctx.scheduler.runAfter(0, internal.users.deleteUserData, {
userId: user._id,
});
return null;
},
});
❌ WRONG:
export const transferFunds = action({
args: { from: v.id("accounts"), to: v.id("accounts"), amount: v.number() },
returns: v.null(),
handler: async (ctx, args) => {
// ❌ These are separate transactions - could leave inconsistent state!
await ctx.runMutation(internal.accounts.debit, {
accountId: args.from,
amount: args.amount,
});
// If this fails, money was debited but not credited!
await ctx.runMutation(internal.accounts.credit, {
accountId: args.to,
amount: args.amount,
});
return null;
},
});
✅ CORRECT:
// Single atomic mutation
export const transferFunds = mutation({
args: { from: v.id("accounts"), to: v.id("accounts"), amount: v.number() },
returns: v.null(),
handler: async (ctx, args) => {
// ✅ All in one transaction - all succeed or all fail
const fromAccount = await ctx.db.get(args.from);
const toAccount = await ctx.db.get(args.to);
if (!fromAccount || !toAccount) throw new Error("Account not found");
if (fromAccount.balance < args.amount)
throw new Error("Insufficient funds");
await ctx.db.patch(args.from, {
balance: fromAccount.balance - args.amount,
});
await ctx.db.patch(args.to, { balance: toAccount.balance + args.amount });
return null;
},
});
❌ WRONG:
export default defineSchema({
messages: defineTable({
channelId: v.id("channels"),
authorId: v.id("users"),
content: v.string(),
})
.index("by_channel", ["channelId"]) // ❌ Redundant!
.index("by_channel_author", ["channelId", "authorId"]),
});
✅ CORRECT:
export default defineSchema({
messages: defineTable({
channelId: v.id("channels"),
authorId: v.id("users"),
content: v.string(),
})
// ✅ Single compound index serves both query patterns
.index("by_channel_author", ["channelId", "authorId"]),
});
// Use prefix matching for channel-only queries:
// .withIndex("by_channel_author", (q) => q.eq("channelId", id))
❌ WRONG:
export const getMessage = query({
args: { messageId: v.string() }, // ❌ Should be v.id()
returns: v.null(),
handler: async (ctx, args) => {
// Type error or runtime error
return await ctx.db.get(args.messageId as Id<"messages">);
},
});
✅ CORRECT:
export const getMessage = query({
args: { messageId: v.id("messages") }, // ✅ Proper ID type
returns: v.union(
v.object({
_id: v.id("messages"),
_creationTime: v.number(),
content: v.string(),
}),
v.null()
),
handler: async (ctx, args) => {
return await ctx.db.get(args.messageId);
},
});
❌ WRONG:
export const processWithRetry = internalAction({
args: { jobId: v.id("jobs"), attempt: v.number() },
returns: v.null(),
handler: async (ctx, args) => {
try {
// Process...
} catch (error) {
if (args.attempt < 5) {
// ❌ Fixed delay causes thundering herd!
await ctx.scheduler.runAfter(5000, internal.jobs.processWithRetry, {
jobId: args.jobId,
attempt: args.attempt + 1,
});
}
}
return null;
},
});
✅ CORRECT:
export const processWithRetry = internalAction({
args: { jobId: v.id("jobs"), attempt: v.number() },
returns: v.null(),
handler: async (ctx, args) => {
try {
// Process...
} catch (error) {
if (args.attempt < 5) {
// ✅ Exponential backoff + jitter
const baseDelay = Math.pow(2, args.attempt) * 1000;
const jitter = Math.random() * 1000;
await ctx.scheduler.runAfter(
baseDelay + jitter,
internal.jobs.processWithRetry,
{
jobId: args.jobId,
attempt: args.attempt + 1,
}
);
}
}
return null;
},
});
returns validator on every function.filter()take(n) for potentially large queriesv.id("table") for document ID argumentsinternalMutation/internalAction for sensitive operationsfetch() in mutationsctx.db in actions.filter() on database queries.collect() without limits on large tablesv.bigint() (deprecated, use v.int64())any type (ESLint rule enforced)Before submitting Convex code, verify:
returns validators.filter()).collect() calls are bounded with .take(n)v.id("tableName")ctx.runQuery/ctx.runMutation for DB accessany types in the codebaseWeekly Installs
62
Repository
GitHub Stars
16
First Seen
Jan 20, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode54
claude-code52
codex51
gemini-cli51
github-copilot46
cursor44
Node.js 环境配置指南:多环境管理、类型安全与最佳实践
10,500 周安装
Symfony API Platform过滤器使用指南 - 合约设计、序列化与安全最佳实践
210 周安装
Skill Creator - Claude AI技能开发指南与最佳实践 | 模块化AI工作流扩展
211 周安装
Sentry 告警创建指南:使用 API 自动化设置监控通知(Slack/邮件/PagerDuty)
209 周安装
Excel报表生成器 - 自动化生成专业Excel报告,支持CSV、数据库、Python数据源
212 周安装
市场分析师技能:基于Reddit情感分析识别市场机会、预测爆款与战略建议
45 周安装
小红书数据分析工具:热门笔记发现、关键词监控、趋势分析与博主研究
212 周安装