mcpField
C
convex-schema-validators

convex-schema-validators

github.com/op0aiデータ・データベース1738 回インストール41 週間前に更新
リポジトリ

convex-schema-validators について

TypeScript で型安全な Convex アプリケーションを開発する人向けのガイドスキルです。スキーマとバリデーターの設計、関数の戻り値検証、インデックス、よくある問題を解説します。

主な機能

  1. 01スキーマとテーブルバリデーターの設計
  2. 02関数の引数と戻り値の検証
  3. 03Convex のドキュメント型とコンテキスト型の利用
  4. 04インデックスの設計とクエリ
  5. 05バリデーターのよくある問題の確認

活用シーン

  1. 01convex/schema.ts の作成や変更
  2. 02クエリ、ミューテーション、アクションへのバリデーター追加
  3. 03ドキュメント ID とデータベース結果の型指定
  4. 04クエリ向けインデックス設計の改善

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/op0ai/claude-skills --skill convex-schema-validators

インストール後、Claude Code で/convex-schema-validatorsを入力して読み込まれたか確認します。

詳細

Convex のスキーマとバリデーターのガイド

概要

Convex では、型安全性を実現するために、組み込みバリデーターを使ったスキーマファーストのアプローチを採用しています。このスキルでは、スキーマ設計、バリデーターパターン、TypeScript の型との統合、型安全な Convex 開発のベストプラクティスについて説明します。

TypeScript:any 型は絶対に使用しない

重大なルール: このコードベースでは @typescript-eslint/no-explicit-any が有効になっています。any を使用すると、ビルドに失敗します。

❌ 間違い:

const data: any = await ctx.db.get(id);
function process(items: any[]) { ... }

✅ 正しい例:

const data: Doc<"users"> | null = await ctx.db.get(id);
function process(items: Doc<"items">[]) { ... }

このスキルを使う場面

次のような場合に、このスキルを使用します。

  • convex/schema.ts を作成または変更するとき
  • 関数の引数と戻り値に対するバリデーターを定義するとき
  • ドキュメント ID と型を扱うとき
  • 効率的なクエリのためにインデックスを設定するとき
  • オプションフィールドとユニオンを扱うとき
  • Convex の型を TypeScript と統合するとき

スキーマの定義

基本的なスキーマ構造
// 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(),
    avatarUrl: v.optional(v.string()),
    role: v.union(v.literal("admin"), v.literal("user")),
    createdAt: v.number(),
  })
    .index("by_email", ["email"])
    .index("by_role", ["role"]),

  messages: defineTable({
    authorId: v.id("users"),
    channelId: v.id("channels"),
    content: v.string(),
    isDeleted: v.boolean(),
  })
    .index("by_channel", ["channelId"])
    .index("by_author", ["authorId"])
    .index("by_channel_author", ["channelId", "authorId"]),

  channels: defineTable({
    name: v.string(),
    members: v.array(v.id("users")),
    isPrivate: v.boolean(),
  }),
});
テーブル定義のパターン
// defineTable takes a validator object
defineTable({
  field1: v.string(),
  field2: v.number(),
});

// Chain indexes after defineTable
defineTable({
  userId: v.id("users"),
  status: v.string(),
})
  .index("by_user", ["userId"])
  .index("by_status", ["status"])
  .index("by_user_status", ["userId", "status"]);

// Search indexes for full-text search
defineTable({
  title: v.string(),
  body: v.string(),
}).searchIndex("search_body", {
  searchField: "body",
  filterFields: ["title"],
});

バリデーターのリファレンス

プリミティブバリデーター
import { v } from "convex/values";

v.string(); // string
v.number(); // number (float64)
v.boolean(); // boolean
v.null(); // null literal
v.int64(); // 64-bit integer (NOT v.bigint() - deprecated!)
v.bytes(); // ArrayBuffer
複雑なバリデーター
// Document IDs
v.id("tableName"); // Id<"tableName">

// Arrays
v.array(v.string()); // string[]
v.array(v.id("users")); // Id<"users">[]
v.array(v.object({ x: v.number() })); // { x: number }[]

// Objects
v.object({
  name: v.string(),
  age: v.number(),
  email: v.optional(v.string()),
});

// Records (string keys, typed values)
v.record(v.string(), v.number()); // Record<string, number>
v.record(v.id("users"), v.string()); // Record<Id<"users">, string>

// Unions (OR types)
v.union(v.string(), v.null()); // string | null
v.union(v.literal("a"), v.literal("b")); // "a" | "b"

// Optionals (field may be missing)
v.optional(v.string()); // string | undefined

// Literals (exact values)
v.literal("active"); // "active" literal type
v.literal(42); // 42 literal type
v.literal(true); // true literal type

// Any (escape hatch - avoid if possible)
v.any(); // any (use sparingly!)
よく使われるバリデーターパターン
// Nullable field (can be null)
status: v.union(v.string(), v.null());

// Optional field (may not exist)
nickname: v.optional(v.string());

// Optional AND nullable
deletedAt: v.optional(v.union(v.number(), v.null()));

// Enum-like unions
role: v.union(v.literal("admin"), v.literal("moderator"), v.literal("user"));

// Nested objects
settings: v.object({
  theme: v.union(v.literal("light"), v.literal("dark")),
  notifications: v.object({
    email: v.boolean(),
    push: v.boolean(),
  }),
});

// Array of objects
members: v.array(
  v.object({
    userId: v.id("users"),
    role: v.string(),
    joinedAt: v.number(),
  })
);

関数のバリデーター

重大:すべての関数に returns バリデーターを指定する必要があります
// ❌ WRONG: Missing returns
export const foo = mutation({
  args: {},
  handler: async (ctx) => {
    // implicitly returns undefined
  },
});

// ✅ CORRECT: Explicit v.null()
export const foo = mutation({
  args: {},
  returns: v.null(),
  handler: async (ctx) => {
    return null;
  },
});
バリデーターを使ったクエリ
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(),
      role: 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 createUser = mutation({
  args: {
    name: v.string(),
    email: v.string(),
    role: v.optional(v.union(v.literal("admin"), v.literal("user"))),
  },
  returns: v.id("users"),
  handler: async (ctx, args) => {
    return await ctx.db.insert("users", {
      name: args.name,
      email: args.email,
      role: args.role ?? "user",
      createdAt: Date.now(),
    });
  },
});
バリデーターを使ったアクション
import { action } from "./_generated/server";
import { v } from "convex/values";

export const processImage = action({
  args: {
    imageUrl: v.string(),
    options: v.object({
      width: v.number(),
      height: v.number(),
      format: v.union(v.literal("png"), v.literal("jpeg")),
    }),
  },
  returns: v.object({
    processedUrl: v.string(),
    size: v.number(),
  }),
  handler: async (ctx, args) => {
    // Process image...
    return {
      processedUrl: "https://...",
      size: 1024,
    };
  },
});

TypeScript の型

型のインポート
import { Doc, Id } from "./_generated/dataModel";

// Document type for a table
type User = Doc<"users">;
// {
//   _id: Id<"users">;
//   _creationTime: number;
//   name: string;
//   email: string;
//   ...
// }

// ID type for a table
type UserId = Id<"users">;
コードでの型の使用
import { Doc, Id } from "./_generated/dataModel";

// Function parameter types
async function getUserName(
  ctx: QueryCtx,
  userId: Id<"users">
): Promise<string | null> {
  const user = await ctx.db.get(userId);
  return user?.name ?? null;
}

// Variable types
const users: Doc<"users">[] = await ctx.db.query("users").collect();

// Record with Id keys
const userMap: Record<Id<"users">, string> = {};
for (const user of users) {
  userMap[user._id] = user.name;
}
コンテキストの型
import { QueryCtx, MutationCtx, ActionCtx } from "./_generated/server";

// Query context - read-only
async function readUser(ctx: QueryCtx, id: Id<"users">) {
  return await ctx.db.get(id);
}

// Mutation context - read and write
async function createUser(ctx: MutationCtx, name: string) {
  return await ctx.db.insert("users", { name, createdAt: Date.now() });
}

// Action context - no db, uses runQuery/runMutation
async function processUser(ctx: ActionCtx, id: Id<"users">) {
  const user = await ctx.runQuery(internal.users.getById, { id });
  // ...
}

インデックスの設計

インデックスの命名規則

インデックス名にはすべてのフィールドを含めます:by_field1_and_field2_and_field3

// Schema
export default defineSchema({
  messages: defineTable({
    channelId: v.id("channels"),
    authorId: v.id("users"),
    content: v.string(),
    isDeleted: v.boolean(),
  })
    // ✅ This single index serves THREE query patterns:
    // 1. All messages in channel: .eq("channelId", id)
    // 2. Messages by author in channel: .eq("channelId", id).eq("authorId", id)
    // 3. Non-deleted messages by author: .eq("channelId", id).eq("authorId", id).eq("isDeleted", false)
    .index("by_channel_author_deleted", ["channelId", "authorId", "isDeleted"]),
});

// ❌ REDUNDANT: Don't create by_channel if you have by_channel_author_deleted
// The compound index can serve channel-only queries by partial prefix match
インデックスの使用
// Using indexes in queries
const messages = await ctx.db
  .query("messages")
  .withIndex("by_channel_author_deleted", (q) =>
    q.eq("channelId", channelId).eq("authorId", authorId).eq("isDeleted", false)
  )
  .collect();

// Partial prefix match (uses first field only)
const allChannelMessages = await ctx.db
  .query("messages")
  .withIndex("by_channel_author_deleted", (q) => q.eq("channelId", channelId))
  .collect();

スキーマからのバリデーターの抽出

スキーマバリデーターの再利用
// convex/schema.ts
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";

// Define shared validators
export const userValidator = v.object({
  name: v.string(),
  email: v.string(),
  role: v.union(v.literal("admin"), v.literal("user")),
});

export default defineSchema({
  users: defineTable(userValidator),
});
// convex/users.ts
import { mutation, query } from "./_generated/server";
import { v } from "convex/values";
import schema from "./schema";

// Extract validator from schema and extend with system fields
const userDoc = schema.tables.users.validator.extend({
  _id: v.id("users"),
  _creationTime: v.number(),
});

export const getUser = query({
  args: { userId: v.id("users") },
  returns: v.union(userDoc, v.null()),
  handler: async (ctx, args) => {
    return await ctx.db.get(args.userId);
  },
});

よく使われるパターン

パターン 1:ステータスの列挙型
// Schema
const statusValidator = v.union(
  v.literal("pending"),
  v.literal("processing"),
  v.literal("completed"),
  v.literal("failed")
);

export default defineSchema({
  jobs: defineTable({
    status: statusValidator,
    data: v.string(),
  }).index("by_status", ["status"]),
});

// Usage in functions
export const getJobsByStatus = query({
  args: {
    status: v.union(
      v.literal("pending"),
      v.literal("processing"),
      v.literal("completed"),
      v.literal("failed")
    ),
  },
  returns: v.array(
    v.object({
      _id: v.id("jobs"),
      _creationTime: v.number(),
      status: v.string(),
      data: v.string(),
    })
  ),
  handler: async (ctx, args) => {
    return await ctx.db
      .query("jobs")
      .withIndex("by_status", (q) => q.eq("status", args.status))
      .collect();
  },
});
パターン 2:ポリモーフィックなドキュメント
// Schema with discriminated union pattern
export default defineSchema({
  notifications: defineTable({
    userId: v.id("users"),
    type: v.union(
      v.literal("message"),
      v.literal("mention"),
      v.literal("system")
    ),
    // Common fields
    read: v.boolean(),
    createdAt: v.number(),
    // Type-specific data stored as object
    data: v.union(
      v.object({ type: v.literal("message"), messageId: v.id("messages") }),
      v.object({
        type: v.literal("mention"),
        messageId: v.id("messages"),
        mentionedBy: v.id("users"),
      }),
      v.object({
        type: v.literal("system"),
        title: v.string(),
        body: v.string(),
      })
    ),
  }).index("by_user", ["userId"]),
});
パターン 3:タイムスタンプパターン
// Helper for timestamp fields
const timestampsValidator = {
  createdAt: v.number(),
  updatedAt: v.number(),
};

export default defineSchema({
  posts: defineTable({
    title: v.string(),
    body: v.string(),
    authorId: v.id("users"),
    ...timestampsValidator,
  }),
});
パターン 4:ソフトデリート
export default defineSchema({
  items: defineTable({
    content: v.string(),
    deletedAt: v.optional(v.number()),
  }).index("by_active", ["deletedAt"]),
});

// Query active items only
const activeItems = await ctx.db
  .query("items")
  .withIndex("by_active", (q) => q.eq("deletedAt", undefined))
  .collect();

よくある落とし穴

落とし穴 1:v.bigint() を使用する(非推奨)

❌ 間違い:

export default defineSchema({
  counters: defineTable({
    value: v.bigint(), // ❌ Deprecated!
  }),
});

✅ 正しい例:

export default defineSchema({
  counters: defineTable({
    value: v.int64(), // ✅ Use v.int64()
  }),
});
落とし穴 2:戻り値のバリデーターにシステムフィールドがない

❌ 間違い:

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);
  },
});

✅ 正しい例:

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);
  },
});
落とし穴 3:v.id() の代わりに string を使用する

❌ 間違い:

export const getMessage = query({
  args: { messageId: v.string() }, // ❌ Should be v.id()
  returns: v.null(),
  handler: async (ctx, args) => {
    // Type error: can't use string as Id
    return await ctx.db.get(args.messageId);
  },
});

✅ 正しい例:

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);
  },
});
落とし穴 4:冗長なインデックス

❌ 間違い:

export default defineSchema({
  messages: defineTable({
    channelId: v.id("channels"),
    authorId: v.id("users"),
  })
    .index("by_channel", ["channelId"]) // ❌ Redundant!
    .index("by_channel_author", ["channelId", "authorId"]),
});

✅ 正しい例:

export default defineSchema({
  messages: defineTable({
    channelId: v.id("channels"),
    authorId: v.id("users"),
  })
    // ✅ Single compound index serves both queries
    .index("by_channel_author", ["channelId", "authorId"]),
});
// Use .eq("channelId", id) for channel-only queries (prefix match)
// Use .eq("channelId", id).eq("authorId", authorId) for both

クイックリファレンス

バリデーター早見表
型バリデーターTypeScript
文字列v.string()string
数値v.number()number
ブール値v.boolean()boolean
Nullv.null()null
64 ビット整数v.int64()bigint
バイト列v.bytes()ArrayBuffer
ドキュメント IDv.id("table")Id<"table">
配列v.array(v.string())string[]
オブジェクトv.object({ x: v.number() }){ x: number }
レコードv.record(v.string(), v.number())Record<string, number>
ユニオンv.union(v.string(), v.null())string | null
オプションv.optional(v.string())string | undefined
リテラルv.literal("active")"active"
型インポート早見表
// Document and ID types
import { Doc, Id } from "./_generated/dataModel";

// Context types
import { QueryCtx, MutationCtx, ActionCtx } from "./_generated/server";

// Function builders
import { query, mutation, action } from "./_generated/server";
import {
  internalQuery,
  internalMutation,
  internalAction,
} from "./_generated/server";

// Validators
import { v } from "convex/values";

// Schema builders
import { defineSchema, defineTable } from "convex/server";

コメント