Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
GraphQL Subscriptions for Antigravity

GraphQL Subscriptions for Antigravity

Build real-time features with GraphQL subscriptions using WebSocket connections and efficient data broadcasting.

GraphQLSubscriptionsWebSocketReal-timeTypeScript
by Antigravity Team
⭐0Stars
👁️1Views
.antigravity
# GraphQL Subscriptions for Google Antigravity

GraphQL subscriptions enable real-time data updates over WebSocket connections. This guide covers subscription implementation optimized for Google Antigravity development.

## Apollo Server Subscription Setup

Configure Apollo Server with subscriptions:

```typescript
// lib/graphql/server.ts
import { ApolloServer } from "@apollo/server";
import { expressMiddleware } from "@apollo/server/express4";
import { ApolloServerPluginDrainHttpServer } from "@apollo/server/plugin/drainHttpServer";
import { makeExecutableSchema } from "@graphql-tools/schema";
import { WebSocketServer } from "ws";
import { useServer } from "graphql-ws/lib/use/ws";
import { PubSub } from "graphql-subscriptions";
import express from "express";
import { createServer } from "http";

export const pubsub = new PubSub();

const typeDefs = `#graphql
  type Message {
    id: ID!
    content: String!
    author: User!
    createdAt: String!
  }

  type User {
    id: ID!
    name: String!
    avatar: String
  }

  type Query {
    messages(channelId: ID!): [Message!]!
  }

  type Mutation {
    sendMessage(channelId: ID!, content: String!): Message!
  }

  type Subscription {
    messageAdded(channelId: ID!): Message!
    userTyping(channelId: ID!): User!
  }
`;

const resolvers = {
  Query: {
    messages: async (_, { channelId }, { db }) => {
      return db.message.findMany({
        where: { channelId },
        include: { author: true },
        orderBy: { createdAt: "desc" },
        take: 50,
      });
    },
  },
  Mutation: {
    sendMessage: async (_, { channelId, content }, { db, user }) => {
      const message = await db.message.create({
        data: {
          content,
          channelId,
          authorId: user.id,
        },
        include: { author: true },
      });

      pubsub.publish(`MESSAGE_ADDED_${channelId}`, {
        messageAdded: message,
      });

      return message;
    },
  },
  Subscription: {
    messageAdded: {
      subscribe: (_, { channelId }) => {
        return pubsub.asyncIterator(`MESSAGE_ADDED_${channelId}`);
      },
    },
    userTyping: {
      subscribe: (_, { channelId }) => {
        return pubsub.asyncIterator(`USER_TYPING_${channelId}`);
      },
    },
  },
};

export async function createGraphQLServer() {
  const app = express();
  const httpServer = createServer(app);
  const schema = makeExecutableSchema({ typeDefs, resolvers });

  // WebSocket server for subscriptions
  const wsServer = new WebSocketServer({
    server: httpServer,
    path: "/graphql",
  });

  const serverCleanup = useServer(
    {
      schema,
      context: async (ctx) => {
        const token = ctx.connectionParams?.authorization as string;
        const user = await validateToken(token);
        return { user };
      },
    },
    wsServer
  );

  const server = new ApolloServer({
    schema,
    plugins: [
      ApolloServerPluginDrainHttpServer({ httpServer }),
      {
        async serverWillStart() {
          return {
            async drainServer() {
              await serverCleanup.dispose();
            },
          };
        },
      },
    ],
  });

  await server.start();
  app.use("/graphql", expressMiddleware(server));

  return httpServer;
}
```

## Redis PubSub for Scalability

Use Redis for multi-instance pub/sub:

```typescript
// lib/graphql/redis-pubsub.ts
import { RedisPubSub } from "graphql-redis-subscriptions";
import Redis from "ioredis";

const options = {
  host: process.env.REDIS_HOST,
  port: parseInt(process.env.REDIS_PORT || "6379"),
  password: process.env.REDIS_PASSWORD,
  retryStrategy: (times: number) => Math.min(times * 50, 2000),
};

export const pubsub = new RedisPubSub({
  publisher: new Redis(options),
  subscriber: new Redis(options),
});

// With filtering support
export const EVENTS = {
  MESSAGE_ADDED: "MESSAGE_ADDED",
  USER_TYPING: "USER_TYPING",
  PRESENCE_CHANGED: "PRESENCE_CHANGED",
};

// Subscription with filtering
const resolvers = {
  Subscription: {
    messageAdded: {
      subscribe: withFilter(
        () => pubsub.asyncIterator(EVENTS.MESSAGE_ADDED),
        (payload, variables) => {
          return payload.messageAdded.channelId === variables.channelId;
        }
      ),
    },
  },
};
```

## Client-Side Subscription Hook

Implement React hooks for subscriptions:

```typescript
// hooks/useSubscription.ts
import { useSubscription, gql } from "@apollo/client";

const MESSAGE_SUBSCRIPTION = gql`
  subscription OnMessageAdded($channelId: ID!) {
    messageAdded(channelId: $channelId) {
      id
      content
      author {
        id
        name
        avatar
      }
      createdAt
    }
  }
`;

export function useMessageSubscription(channelId: string) {
  const { data, loading, error } = useSubscription(MESSAGE_SUBSCRIPTION, {
    variables: { channelId },
    onSubscriptionData: ({ subscriptionData }) => {
      const newMessage = subscriptionData.data?.messageAdded;
      if (newMessage) {
        // Update cache or state
        console.log("New message:", newMessage);
      }
    },
  });

  return { newMessage: data?.messageAdded, loading, error };
}

// Chat component using subscription
function ChatRoom({ channelId }: { channelId: string }) {
  const [messages, setMessages] = useState<Message[]>([]);
  
  useMessageSubscription(channelId);

  // Subscription automatically updates Apollo cache
  const { data } = useQuery(GET_MESSAGES, {
    variables: { channelId },
  });

  return (
    <div className="flex flex-col h-full">
      <div className="flex-1 overflow-y-auto">
        {data?.messages.map((message) => (
          <MessageBubble key={message.id} message={message} />
        ))}
      </div>
      <MessageInput channelId={channelId} />
    </div>
  );
}
```

## Best Practices

When implementing GraphQL subscriptions in Antigravity projects, use Redis PubSub for horizontal scaling, implement proper authentication for WebSocket connections, handle reconnection gracefully, use subscription filtering to reduce payload, clean up subscriptions on component unmount, monitor subscription connections for memory leaks, and implement rate limiting on subscription events.

When to Use This Prompt

This GraphQL prompt is ideal for developers working on:

  • GraphQL applications requiring modern best practices and optimal performance
  • Projects that need production-ready GraphQL code with proper error handling
  • Teams looking to standardize their graphql development workflow
  • Developers wanting to learn industry-standard GraphQL patterns and techniques

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 graphql implementations.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the GraphQL code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this GraphQL prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

You can modify the prompt by adding specific requirements, constraints, or preferences. For GraphQL projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...