Subscriptions & Real-time — GraphQL

GraphQL Subscriptions Subscriptions adalah cara GraphQL menangani real-time data. Client "subscribe" ke event, server push update via WebSocket. Schema type Sub

GraphQL Subscriptions

Subscriptions adalah cara GraphQL menangani real-time data. Client "subscribe" ke event, server push update via WebSocket.

Schema

type Subscription {
  messageAdded(channelId: ID!): Message!
  userStatusChanged: UserStatus!
  orderUpdated(orderId: ID!): Order!
}

Server Setup (Apollo)

import { PubSub } from "graphql-subscriptions";

const pubsub = new PubSub();

const resolvers = {
  Mutation: {
    sendMessage: async (_, { channelId, text }, { user }) => {
      const message = await db.messages.create({
        data: { channelId, text, authorId: user.id },
      });

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

      return message;
    },
  },

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

Client

// Apollo Client subscription
const MESSAGE_SUBSCRIPTION = gql`
  subscription OnMessageAdded($channelId: ID!) {
    messageAdded(channelId: $channelId) {
      id
      text
      author {
        name
      }
    }
  }
`;

function ChatRoom({ channelId }) {
  const { data } = useSubscription(MESSAGE_SUBSCRIPTION, {
    variables: { channelId },
  });

  // data.messageAdded updates whenever new message arrives
}

Production Considerations

Yang akan kamu pelajari