mcpField
C
components-guide

components-guide

github.com/get-convex开发69546 次安装1 天前更新
代码仓库

关于 components-guide

面向 Convex 开发者的组件设计与使用指南,介绍如何将后端功能封装为拥有独立数据和 API 边界的组件。内容涵盖安装配置、组件协作及自定义组件实践。

主要功能

  1. 01介绍组件的数据与函数隔离
  2. 02说明安装和应用配置
  3. 03展示父组件与同级组件协作
  4. 04提供自定义组件结构示例
  5. 05涵盖组件边界与复用实践

适用场景

  1. 01将存储或通知功能封装为组件
  2. 02在应用中配置并使用 npm 组件
  3. 03规划可跨项目复用的后端功能

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/get-convex/agent-skills --skill components-guide

安装后在 Claude Code 中输入/components-guide确认已加载。

详细介绍

Convex 组件指南

使用组件封装功能,构建易于维护、可复用的后端。

什么是 Convex 组件?

组件是自包含的小型后端,包含:

  • 自有数据库架构
  • 自有函数(查询、变更、操作)
  • 自有数据(隔离的表)
  • 明确的 API 边界

可以把它们看作: 后端的 npm 包,或无需处理部署复杂性的微服务。

为什么使用组件?

传统方式(单体)
convex/
  users.ts (500 lines)
  files.ts (600 lines - upload, storage, permissions, rate limiting)
  payments.ts (400 lines - Stripe, webhooks, billing)
  notifications.ts (300 lines)
  analytics.ts (200 lines)

Total: One big codebase, everything mixed together
组件方式(封装)
convex/
  components/
    storage/ (File uploads - reusable)
    billing/ (Payments - reusable)
    notifications/ (Alerts - reusable)
    analytics/ (Tracking - reusable)
  convex.config.ts (Wire components together)
  domain/ (Your actual business logic)
    users.ts (50 lines - uses components)
    projects.ts (75 lines - uses components)

Total: Clean, focused, reusable

快速开始

1. 安装组件
# Official components from npm
npm install @convex-dev/ratelimiter
2. 在 convex.config.ts 中配置
import { defineApp } from "convex/server";
import ratelimiter from "@convex-dev/ratelimiter/convex.config";

export default defineApp({
  components: {
    ratelimiter,
  },
});
3. 在代码中使用
import { components } from "./_generated/api";

export const createPost = mutation({
  handler: async (ctx, args) => {
    // Use the component
    await components.ratelimiter.check(ctx, {
      key: `user:${ctx.user._id}`,
      limit: 10,
      period: 60000, // 10 requests per minute
    });

    return await ctx.db.insert("posts", args);
  },
});

同级组件模式

多个组件在同一级协同工作:

// convex.config.ts
export default defineApp({
  components: {
    // Sibling components - each handles one concern
    auth: authComponent,
    storage: storageComponent,
    payments: paymentsComponent,
    emails: emailComponent,
    analytics: analyticsComponent,
  },
});
示例:使用同级组件实现完整功能
// convex/subscriptions.ts
import { components } from "./_generated/api";

export const subscribe = mutation({
  args: { plan: v.string() },
  handler: async (ctx, args) => {
    // 1. Verify authentication (auth component)
    const user = await components.auth.getCurrentUser(ctx);

    // 2. Create payment (payments component)
    const subscription = await components.payments.createSubscription(ctx, {
      userId: user._id,
      plan: args.plan,
      amount: getPlanAmount(args.plan),
    });

    // 3. Track conversion (analytics component)
    await components.analytics.track(ctx, {
      event: "subscription_created",
      userId: user._id,
      plan: args.plan,
    });

    // 4. Send confirmation (emails component)
    await components.emails.send(ctx, {
      to: user.email,
      template: "subscription_welcome",
      data: { plan: args.plan },
    });

    // 5. Store subscription in main app
    await ctx.db.insert("subscriptions", {
      userId: user._id,
      paymentId: subscription.id,
      plan: args.plan,
      status: "active",
    });

    return subscription;
  },
});

官方组件

浏览组件目录:

身份验证
  • @convex-dev/better-auth - Better Auth 集成
存储
  • @convex-dev/r2 - Cloudflare R2 文件存储
  • @convex-dev/storage - 文件上传/下载
支付
  • @convex-dev/polar - Polar 计费和订阅
AI
  • @convex-dev/agent - AI Agent 工作流
  • @convex-dev/embeddings - 向量存储和搜索
后端实用工具
  • @convex-dev/ratelimiter - 速率限制
  • @convex-dev/aggregate - 数据聚合
  • @convex-dev/action-cache - 缓存操作结果
  • @convex-dev/sharded-counter - 分布式计数器
  • @convex-dev/migrations - 架构迁移
  • @convex-dev/workflow - 工作流编排

创建自己的组件

何时创建组件

适合创建的情况:

  • 功能自成一体
  • 计划在多个项目中复用
  • 希望与团队或社区分享
  • 功能复杂,且有自己的数据模型
  • 封装第三方集成

不适合创建的情况:

  • 一次性的业务逻辑
  • 与主应用紧密耦合
  • 简单的实用函数
结构
mkdir -p convex/components/notifications
// convex/components/notifications/convex.config.ts
import { defineComponent } from "convex/server";

export default defineComponent("notifications");
// convex/components/notifications/schema.ts
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";

export default defineSchema({
  notifications: defineTable({
    userId: v.id("users"),
    message: v.string(),
    read: v.boolean(),
    createdAt: v.number(),
  })
    .index("by_user", ["userId"])
    .index("by_user_and_read", ["userId", "read"]),
});
// convex/components/notifications/send.ts
import { mutation } from "./_generated/server";
import { v } from "convex/values";

export const send = mutation({
  args: {
    userId: v.id("users"),
    message: v.string(),
  },
  handler: async (ctx, args) => {
    await ctx.db.insert("notifications", {
      userId: args.userId,
      message: args.message,
      read: false,
      createdAt: Date.now(),
    });
  },
});

export const markRead = mutation({
  args: { notificationId: v.id("notifications") },
  handler: async (ctx, args) => {
    await ctx.db.patch(args.notificationId, { read: true });
  },
});
// convex/components/notifications/read.ts
import { query } from "./_generated/server";
import { v } from "convex/values";

export const list = query({
  args: { userId: v.id("users") },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("notifications")
      .withIndex("by_user", q => q.eq("userId", args.userId))
      .order("desc")
      .collect();
  },
});

export const unreadCount = query({
  args: { userId: v.id("users") },
  handler: async (ctx, args) => {
    const unread = await ctx.db
      .query("notifications")
      .withIndex("by_user_and_read", q =>
        q.eq("userId", args.userId).eq("read", false)
      )
      .collect();

    return unread.length;
  },
});

组件通信模式

父级到组件(推荐)
// Main app calls component
await components.storage.upload(ctx, file);
await components.analytics.track(ctx, event);
父级到多个同级组件(推荐)
// Main app orchestrates multiple components
await components.auth.verify(ctx);
const file = await components.storage.upload(ctx, data);
await components.notifications.send(ctx, message);
组件接收父级数据(推荐)
// Pass IDs from parent's tables to component
await components.audit.log(ctx, {
  userId: user._id, // From parent's users table
  action: "delete",
  resourceId: task._id, // From parent's tasks table
});

// Component stores these as strings/IDs
// but doesn't access parent tables directly
组件访问父级表(不推荐)
// Inside component code - DON'T DO THIS
const user = await ctx.db.get(userId); // Error! Can't access parent tables
同级组件之间(不推荐)

组件不能直接相互调用。如果需要这种通信,应将它们放在主应用中,或重构设计。

最佳实践

1. 单一职责

每个组件都专注做好一件事:

  • 存储组件处理文件
  • 身份验证组件处理身份验证
  • 不要创建包含所有内容的“utils”组件
2. 明确的 API 接口
// Export only what's needed
export { upload, download, delete } from "./storage";

// Keep internals private
// (Don't export helper functions)
3. 尽量减少耦合
// Good: Pass data as arguments
await components.audit.log(ctx, {
  userId: user._id,
  action: "delete"
});

// Bad: Component accesses parent tables
// (Not even possible, but shows the principle)
4. 为组件设置版本
{
  "name": "@yourteam/notifications-component",
  "version": "1.0.0"
}
5. 编写组件文档

README 应包含:

  • 组件的功能
  • 安装方法
  • 使用方法
  • API 参考
  • 示例

检查清单

  • 浏览组件目录,查找现有解决方案
  • 通过 npm 安装组件:npm install @convex-dev/component-name
  • 在 convex.config.ts 中配置
  • 使用同级组件封装功能
  • 为可复用功能创建自己的组件
  • 保持组件专注(单一职责)
  • 单独测试组件
  • 编写组件 API 文档
  • 正确管理组件版本

评论

支持 Markdown