|
| 1 | +# convex |
| 2 | + |
| 3 | +## Validator Patterns |
| 4 | + |
| 5 | +### DRY Validator Definition |
| 6 | + |
| 7 | +Define validators in a reusable, DRY pattern following the example in `convex/generate_image/generate_same/imageGenerationValidator.ts`: |
| 8 | + |
| 9 | +```typescript |
| 10 | +import { v } from "convex/values" |
| 11 | + |
| 12 | +// Define base fields as a const object |
| 13 | +export const someEntityValidatorFields = { |
| 14 | + workspaceId: v.id("workspace"), |
| 15 | + name: v.string(), |
| 16 | + // ... other fields |
| 17 | +} |
| 18 | + |
| 19 | +// Create base validator |
| 20 | +export const someEntityValidator = v.object(someEntityValidatorFields) |
| 21 | + |
| 22 | +// Create variant with token for mutations/queries |
| 23 | +export const someEntityValidatorWithToken = v.object({ |
| 24 | + ...someEntityValidatorFields, |
| 25 | + token: v.string() |
| 26 | +}) |
| 27 | + |
| 28 | +// Export the type |
| 29 | +export type SomeEntityValidatorType = typeof someEntityValidator.type |
| 30 | +``` |
| 31 | +
|
| 32 | +### Type-Safe ID Definitions |
| 33 | +
|
| 34 | +Use existing type-safe ID definitions like in `convex/auth/IdUser.ts`: |
| 35 | +
|
| 36 | +```typescript |
| 37 | +import type { Id } from "../_generated/dataModel" |
| 38 | + |
| 39 | +export type IdUser = Id<"users"> |
| 40 | +export type IdWorkspace = Id<"workspace"> |
| 41 | +// Add other ID types as needed |
| 42 | +``` |
| 43 | +
|
| 44 | +## Query/Mutation Patterns |
| 45 | +
|
| 46 | +### Function Variants |
| 47 | +
|
| 48 | +Each query/mutation/internalQuery/internalMutation should have a corresponding `Fn` function variant, following the pattern in `convex/auth/crud/findUserByEmailQuery.ts`: |
| 49 | +
|
| 50 | +```typescript |
| 51 | +import type { QueryCtx } from "../../_generated/server" |
| 52 | +import { internalQuery } from "../../_generated/server" |
| 53 | +import { v } from "convex/values" |
| 54 | + |
| 55 | +// Define the query |
| 56 | +export const findUserByEmailQuery = internalQuery({ |
| 57 | + args: { email: v.string() }, |
| 58 | + handler: async (ctx, args): Promise<Doc<"users"> | null> => { |
| 59 | + return findUserByEmailFn(ctx, args.email) |
| 60 | + }, |
| 61 | +}) |
| 62 | + |
| 63 | +// Define the Fn function variant for reuse |
| 64 | +export async function findUserByEmailFn(ctx: QueryCtx, email: string): Promise<Doc<"users"> | null> { |
| 65 | + return await ctx.db |
| 66 | + .query("users") |
| 67 | + .withIndex("email", (q) => q.eq("email", email)) |
| 68 | + .unique() |
| 69 | +} |
| 70 | +``` |
| 71 | + |
| 72 | +### Token Validation |
| 73 | + |
| 74 | +All mutations and queries should include a `token` parameter with validation: |
| 75 | + |
| 76 | +```typescript |
| 77 | +import { v } from "convex/values" |
| 78 | +import { mutation } from "../../_generated/server" |
| 79 | + |
| 80 | +export const someMutation = mutation({ |
| 81 | + args: { |
| 82 | + // Use the validator with token |
| 83 | + ...someEntityValidatorWithToken.fields, |
| 84 | + }, |
| 85 | + handler: async (ctx, args) => { |
| 86 | + // Validate token first |
| 87 | + const user = await validateToken(ctx, args.token) |
| 88 | + if (!user) { |
| 89 | + throw new Error("Invalid token") |
| 90 | + } |
| 91 | + |
| 92 | + // Proceed with mutation logic |
| 93 | + return someMutationFn(ctx, args, user) |
| 94 | + }, |
| 95 | +}) |
| 96 | + |
| 97 | +export async function someMutationFn(ctx: MutationCtx, args: SomeEntityValidatorType, user: Doc<"users">) { |
| 98 | + // Mutation implementation |
| 99 | +} |
| 100 | +``` |
| 101 | + |
| 102 | +## Data Transformation Patterns |
| 103 | + |
| 104 | +### Database to Model Transformation |
| 105 | + |
| 106 | +Create transformation functions to convert database documents to your application models: |
| 107 | + |
| 108 | +```typescript |
| 109 | +import type { UserProfile } from "@/auth/model/UserProfile" |
| 110 | +import type { Doc } from "../../_generated/dataModel" |
| 111 | + |
| 112 | +export function dbUsersToUserProfile(u: Doc<"users">): UserProfile { |
| 113 | + const { _id, _creationTime, ...rest } = u |
| 114 | + return { userId: _id, ...rest } |
| 115 | +} |
| 116 | +``` |
| 117 | + |
| 118 | +## Best Practices |
| 119 | + |
| 120 | +1. **Always use validators** for all query/mutation arguments |
| 121 | +2. **Include token validation** in all public-facing mutations/queries |
| 122 | +3. **Create Fn variants** for all database operations to enable reuse |
| 123 | +4. **Use type-safe IDs** instead of string literals |
| 124 | +5. **Keep validators close** to where they're used |
| 125 | +6. **Export transformation functions** for consistent data conversion |
| 126 | +7. **Follow DRY principles** by defining base validators and extending them |
0 commit comments