К основному содержанию
скилл CX Codex

convex · mindrally — скилл для Claude Code: правила бэкенда Convex

Задаёт агенту правила работы с Convex: запросы, мутации, actions, индексы и файлы. Пригодится, когда бэкенд на Convex уже выбран.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add Mindrally/skills --skill convex -a claude-code
Открыть на GitHub

Что делает convex

Скилл подключает к агенту набор соглашений по Convex — backend-as-a-service на TypeScript. Внутри описаны четыре основных примитива: query, mutation, action и HTTP-роутер, плюс схемы с индексами, cron-задачи и загрузка файлов через ctx.storage.generateUploadUrl().

Агенту задаётся стиль кода: функциональные объявления, интерфейсы вместо типов, union-типы вместо enum, имена вроде isLoading и hasError. Для интерфейса предлагаются Shadcn UI, Radix UI и Tailwind CSS, а useClient, useEffect и useState советуется использовать как можно реже. Ошибки обрабатываются guard-клаузами в начале функции, формы валидируются через Zod.

Отдельный блок — производительность. Фильтры в запросах заменяются индексами: их объявляют в schema.ts методом .index(), а в запросе вызывают .withIndex(). Для больших выборок есть .paginate(), для одного результата — .first() вместо .collect(). Внешние API разрешено вызывать только из actions, но не из queries и mutations — это повод проверить существующий код, если у вас там уже есть fetch внутри query.

Какие задачи решает

  • описать схему таблиц Convex с индексами по статусу и пользователю
  • написать mutation с проверкой авторизации через ctx.auth.getUserIdentity()
  • вынести вызов внешнего API в action вместо query
  • настроить cron-задачу для периодической очистки данных
  • загрузить файл в хранилище Convex и сохранить storageId в базе

Примеры запросов агенту

  • добавь в схему Convex таблицу items с индексами by_status и by_user
  • перепиши этот query так, чтобы он использовал .withIndex() вместо .filter()
  • сделай action для отправки письма через внешний API

Как установить convex

1Через Skills CLI (Vercel)

npx skills add Mindrally/skills --skill convex -a claude-code

2Вручную: положить файлы

~/.claude/skills/convex/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/convex/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора168

graphql-development Набор правил для GraphQL: схема, типизированные клиенты, интеграция с React и Next.js. Пригодится, когда агент пишет резолверы и запросы. CX Codex +1 661установок turborepo Скилл задаёт агенту правила работы с Turborepo: структура воркспейсов, turbo.json, кэш и фильтры задач. Пригодится, когда монорепо уже есть и его надо привести в порядок. CX Codex +1 658установок rollup-bundler Скилл задаёт агенту правила конфигурации Rollup.js: форматы вывода, внешние зависимости, tree-shaking и плагины для сборки библиотек. CX Codex +1 657установок serverless Скилл задаёт агенту правила разработки на FastAPI в микросервисах и serverless-среде: AWS Lambda, Azure Functions, API-шлюзы. CX Codex +1 655установок lerna Скилл задаёт агенту правила Lerna: структура пакетов, версионирование, публикация и запуск скриптов в монорепозитории. CX Codex +1 650установок onchainkit Скилл для ИИ-агента, который помогает собирать onchain-приложения на OnchainKit SDK: компоненты, провайдеры, транзакции и обмен токенов. CX Codex +1 641установок robocorp-cursor-rules Набор правил для ИИ-агента: как писать RPA-автоматизацию на Python под RoboCorp — функционально, с Pydantic и async. CX Codex +1 636установок parcel-bundler Скилл задаёт агенту правила работы со сборщиком Parcel: точки входа, TypeScript, CSS-модули, кэш и продакшен-сборка. Пригодится, когда проект собирается без конфига. CX Codex +1 633установок

Другие версии convex

Похожие

convex-expert convex Скилл для работы с кодом в каталоге convex/: функции, схемы, индексы, валидаторы. Пригодится, когда агент пишет бэкенд на Convex. CX Codex +1 36 200установок convex-best-practices waynesutton Скилл учит агента писать надёжный бэкенд на Convex без конфликтов записи OCC. Помогает настроить валидаторы, индексы и правила @convex-dev/eslint-plugin. CX Codex +1 3 900установок convex-functions waynesutton Пишет query, mutation и action для Convex в объектной форме: с валидаторами args и returns, правильным ctx и обработкой ошибок. CX Codex +1 3 200установок convex-create-component convex Скилл помогает создавать переиспользуемые Convex-компоненты с изолированными таблицами и чётким API. Пригодится, когда нужно выделить backend-логику в отдельный модуль или собрать интеграцию, которая владеет своими данными. CX Codex +1 130 900установок appwrite-python appwrite Подсказывает агенту, как писать серверный код на Python с Appwrite SDK: пользователи, таблицы, хранилище файлов, функции. CX Codex +1 1 100установок replica-backend Jakeschincariol Собирает бэкенд клона приложения: авторизацию, миграции базы, доступы, платежи Stripe, письма и фоновые задачи. Читает replica/architecture.md и ведёт чек-лист в replica/backend.md. CX Codex +1 613установок

Рядом в теме «Бэкенд и API»

Всё по теме «Бэкенд и API» →

Вопросы о convex

Как установить скилл convex в Claude?

Выполните npx skills add Mindrally/skills --skill convex -a claude-code. Файл скилла окажется по пути ~/.claude/skills/convex/SKILL.md.

Что делает скилл convex?

Даёт агенту правила разработки на Convex: как писать queries, mutations и actions, как объявлять схему с индексами, как работать с файлами и cron-задачами.

Можно ли вызывать внешние API из query в Convex?

Нет. Скилл требует выносить побочные эффекты в actions, а queries и mutations оставлять чистыми.

Исходный текст

SKILL.md · Apache-2.0
---
name: convex
description: Guidelines for developing with Convex backend-as-a-service platform, covering queries, mutations, actions, and real-time data patterns
metadata:
  maintainer: Mindrally
  source: https://github.com/Mindrally/skills
---

# Convex Development Guidelines

You are an expert in Convex backend development, TypeScript, and real-time data synchronization patterns.

## General Development Specifications

### Code Style and Structure

- Write concise TypeScript using functional declarations, iterators, and modules
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError)
- Structure code with exported components, subcomponents, helpers, and static types
- Use dash-case for directories with named exports
- Prefer interfaces over types; avoid enums in favor of union types
- Use functional components with declarative JSX patterns

### Error Handling

- Handle errors early in functions with guard clauses
- Log errors appropriately for debugging
- Provide user-friendly error messages
- Use Zod for form validation
- Implement proper error boundaries in React components

### UI Framework Integration

- Use Shadcn UI and Radix UI for component primitives
- Style with Tailwind CSS using responsive, mobile-first design
- Minimize useClient, useEffect, and useState usage
- Leverage React Server Components where applicable
- Use Suspense for loading states and dynamic loading for code splitting

## Convex-Specific Patterns

### Queries

Structure queries using the `query` constructor:

```typescript
import { query } from "./_generated/server";
import { v } from "convex/values";

export const getItems = query({
  args: {
    status: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    // ctx provides: db, storage, auth
    const identity = await ctx.auth.getUserIdentity();

    if (args.status) {
      return await ctx.db
        .query("items")
        .withIndex("by_status", (q) => q.eq("status", args.status))
        .collect();
    }

    return await ctx.db.query("items").collect();
  },
});
```

**Important**: Prefer Convex indexes over filters for better performance. Define indexes in schema.ts using the `.index()` method, then query with `.withIndex()`.

### Mutations

Structure mutations for database writes:

```typescript
import { mutation } from "./_generated/server";
import { v } from "convex/values";

export const createItem = mutation({
  args: {
    title: v.string(),
    description: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) {
      throw new Error("Not authenticated");
    }

    return await ctx.db.insert("items", {
      title: args.title,
      description: args.description,
      userId: identity.subject,
      createdAt: Date.now(),
    });
  },
});
```

### Actions

Use actions for external API calls and side effects:

```typescript
import { action } from "./_generated/server";
import { v } from "convex/values";

export const sendEmail = action({
  args: {
    to: v.string(),
    subject: v.string(),
    body: v.string(),
  },
  handler: async (ctx, args) => {
    // Actions can call external APIs
    const response = await fetch("https://api.email-service.com/send", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(args),
    });

    return response.ok;
  },
});
```

### Schema Definition with Indexes

```typescript
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";

export default defineSchema({
  items: defineTable({
    title: v.string(),
    description: v.optional(v.string()),
    status: v.string(),
    userId: v.string(),
    createdAt: v.number(),
  })
    .index("by_status", ["status"])
    .index("by_user", ["userId"])
    .index("by_user_and_status", ["userId", "status"]),
});
```

### HTTP Router

Define HTTP routes for webhooks and external integrations:

```typescript
import { httpRouter } from "convex/server";
import { httpAction } from "./_generated/server";

const http = httpRouter();

http.route({
  path: "/webhook",
  method: "POST",
  handler: httpAction(async (ctx, request) => {
    const body = await request.json();
    // Process webhook
    return new Response(JSON.stringify({ success: true }), {
      status: 200,
      headers: { "Content-Type": "application/json" },
    });
  }),
});

export default http;
```

### Scheduled Jobs

Implement cron jobs for recurring tasks:

```typescript
import { cronJobs } from "convex/server";
import { internal } from "./_generated/api";

const crons = cronJobs();

// Run every hour
crons.interval(
  "cleanup-old-items",
  { hours: 1 },
  internal.tasks.cleanupOldItems
);

// Run at specific time (daily at midnight UTC)
crons.monthly(
  "monthly-report",
  { day: 1, hourUTC: 0, minuteUTC: 0 },
  internal.reports.generateMonthlyReport
);

export default crons;
```

### File Handling

Three-step process for file uploads:

```typescript
// 1. Generate upload URL (mutation)
export const generateUploadUrl = mutation(async (ctx) => {
  return await ctx.storage.generateUploadUrl();
});

// 2. Client POSTs file to the URL
// const uploadUrl = await generateUploadUrl();
// const response = await fetch(uploadUrl, { method: "POST", body: file });
// const { storageId } = await response.json();

// 3. Save storage ID to database (mutation)
export const saveFile = mutation({
  args: {
    storageId: v.id("_storage"),
    filename: v.string(),
  },
  handler: async (ctx, args) => {
    return await ctx.db.insert("files", {
      storageId: args.storageId,
      filename: args.filename,
    });
  },
});
```

## Best Practices

1. **Always use indexes** for queries that filter or sort data
2. **Validate arguments** using Convex validators (`v.string()`, `v.number()`, etc.)
3. **Check authentication** early in handlers that require it
4. **Use internal functions** for operations that should not be exposed to clients
5. **Leverage real-time subscriptions** - Convex queries automatically update when data changes
6. **Keep mutations small** and focused on single operations
7. **Use actions for side effects** - never call external APIs from queries or mutations
8. **Handle errors gracefully** with proper error messages for users

## Performance Considerations

- Use `.withIndex()` instead of `.filter()` whenever possible
- Paginate large result sets using `.paginate()`
- Use `.first()` instead of `.collect()` when expecting a single result
- Consider data denormalization for frequently accessed data
- Use Convex's built-in caching - avoid implementing your own

© Mindrally · Apache-2.0 · Mindrally/skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой