Master Convex realtime database patterns for Google Antigravity IDE reactive applications
# Convex Realtime Database Patterns for Google Antigravity IDE
Build reactive applications with Convex using Google Antigravity IDE's Gemini 3 assistance. This comprehensive guide covers schema design, queries, mutations, actions, and real-time subscriptions for serverless backends.
## Schema Definition
```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(),
imageUrl: v.optional(v.string()),
tokenIdentifier: v.string(),
role: v.union(v.literal("admin"), v.literal("user")),
})
.index("by_token", ["tokenIdentifier"])
.index("by_email", ["email"]),
channels: defineTable({
name: v.string(),
description: v.optional(v.string()),
createdBy: v.id("users"),
isPrivate: v.boolean(),
members: v.array(v.id("users")),
})
.index("by_creator", ["createdBy"]),
messages: defineTable({
channelId: v.id("channels"),
authorId: v.id("users"),
content: v.string(),
attachments: v.optional(v.array(v.object({
type: v.union(v.literal("image"), v.literal("file")),
url: v.string(),
name: v.string(),
}))),
editedAt: v.optional(v.number()),
deletedAt: v.optional(v.number()),
})
.index("by_channel", ["channelId"])
.index("by_author", ["authorId"]),
reactions: defineTable({
messageId: v.id("messages"),
userId: v.id("users"),
emoji: v.string(),
})
.index("by_message", ["messageId"])
.index("by_user_message", ["userId", "messageId"]),
});
```
## Queries with Real-Time Updates
```typescript
// convex/messages.ts
import { query, mutation } from "./_generated/server";
import { v } from "convex/values";
import { paginationOptsValidator } from "convex/server";
export const list = query({
args: {
channelId: v.id("channels"),
paginationOpts: paginationOptsValidator,
},
handler: async (ctx, args) => {
// Verify user has access to channel
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new Error("Unauthenticated");
const channel = await ctx.db.get(args.channelId);
if (!channel) throw new Error("Channel not found");
const user = await ctx.db
.query("users")
.withIndex("by_token", (q) => q.eq("tokenIdentifier", identity.tokenIdentifier))
.unique();
if (channel.isPrivate && !channel.members.includes(user!._id)) {
throw new Error("Access denied");
}
// Fetch paginated messages
const messages = await ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
.filter((q) => q.eq(q.field("deletedAt"), undefined))
.order("desc")
.paginate(args.paginationOpts);
// Enrich with author info and reactions
const enrichedMessages = await Promise.all(
messages.page.map(async (message) => {
const author = await ctx.db.get(message.authorId);
const reactions = await ctx.db
.query("reactions")
.withIndex("by_message", (q) => q.eq("messageId", message._id))
.collect();
return {
...message,
author: author ? { name: author.name, imageUrl: author.imageUrl } : null,
reactions: groupReactions(reactions),
};
})
);
return {
...messages,
page: enrichedMessages,
};
},
});
export const send = mutation({
args: {
channelId: v.id("channels"),
content: v.string(),
attachments: v.optional(v.array(v.object({
type: v.union(v.literal("image"), v.literal("file")),
url: v.string(),
name: v.string(),
}))),
},
handler: async (ctx, args) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new Error("Unauthenticated");
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");
const messageId = await ctx.db.insert("messages", {
channelId: args.channelId,
authorId: user._id,
content: args.content,
attachments: args.attachments,
});
return messageId;
},
});
```
## Actions for External APIs
```typescript
// convex/actions/ai.ts
import { action } from "../_generated/server";
import { v } from "convex/values";
import { api } from "../_generated/api";
export const generateResponse = action({
args: {
channelId: v.id("channels"),
prompt: v.string(),
},
handler: async (ctx, args) => {
// Call external AI API
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: "gpt-4",
messages: [{ role: "user", content: args.prompt }],
}),
});
const data = await response.json();
const aiMessage = data.choices[0].message.content;
// Store AI response as message
await ctx.runMutation(api.messages.sendAsBot, {
channelId: args.channelId,
content: aiMessage,
});
return aiMessage;
},
});
```
## Best Practices for Google Antigravity IDE
When using Convex with Google Antigravity, define strict schemas for type safety. Use indexes for efficient queries. Implement pagination for large datasets. Separate queries and mutations appropriately. Use actions for external API calls. Let Gemini 3 generate optimized Convex functions from your data requirements.
Google Antigravity's agent mode excels at scaffolding complete Convex backends with proper access control.This Convex prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their convex implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Convex projects, consider mentioning your framework version, coding style, and any specific libraries you're using.