Introduction to GraphQL Subscriptions
GraphQL Subscriptions are a powerful feature of GraphQL that allow you to create real-time updates to your applications. This capability is essential for apps that require immediate data updates, such as chat applications, live feed dashboards, or collaborative tools.
Getting Started with GraphQL Subscriptions
To utilize GraphQL Subscriptions, you need to set up a GraphQL server and client that support the subscription protocol. Popular libraries such as Apollo Server and Apollo Client make it straightforward to implement.
Setting Up Apollo Server
const { ApolloServer, gql } = require('apollo-server'); const { PubSub } = require('graphql-subscriptions'); const pubsub = new PubSub(); const typeDefs = gql` type Message { id: ID! content: String! } type Query { messages: [Message!] } type Mutation { postMessage(content: String!): ID! } type Subscription { messagePosted: Message } `; const resolvers = { Query: { messages: () => messages, }, Mutation: { postMessage: (_, { content }) => { const id = messages.length; const message = { id, content }; messages.push(message); pubsub.publish('MESSAGE_POSTED', { messagePosted: message }); return id; }, }, Subscription: { messagePosted: { subscribe: () => pubsub.asyncIterator(['MESSAGE_POSTED']), }, }, }; const server = new ApolloServer({ typeDefs, resolvers, subscriptions: { path: '/subscriptions', }, }); server.listen().then(({ url, subscriptionsUrl }) => { console.log(`Server ready at ${url}`); console.log(`Subscriptions ready at ${subscriptionsUrl}`); });
Setting Up Apollo Client
import { ApolloClient, InMemoryCache, gql } from '@apollo/client'; import { WebSocketLink } from '@apollo/client/link/ws'; import { split } from '@apollo/client'; import { getMainDefinition } from '@apollo/client/utilities'; const httpLink = new HttpLink({ uri: 'http://localhost:4000/', }); const wsLink = new WebSocketLink({ uri: `ws://localhost:4000/subscriptions`, options: { reconnect: true, }, }); const splitLink = split( ({ query }) => { const definition = getMainDefinition(query); return ( definition.kind === 'OperationDefinition' && definition.operation === 'subscription' ); }, wsLink, httpLink, ); const client = new ApolloClient({ link: splitLink, cache: new InMemoryCache(), }); const MESSAGE_POSTED = gql` subscription OnMessagePosted { messagePosted { id content } } `; client.subscribe({ query: MESSAGE_POSTED }).subscribe({ next({ data }) { console.log(data); }, });
Example Application
Let’s put together a simple chat application to demonstrate the use of GraphQL Subscriptions:
const App = () => { const [messageInput, setMessageInput] = useState(''); const { data, loading } = useSubscription(MESSAGE_POSTED); const [postMessage] = useMutation(gql` mutation($content: String!) { postMessage(content: $content) } `); return (); }Chat
{loading ? "Loading..." : data.messagePosted.map(msg => (setMessageInput(e.target.value)} />{msg.content}))}
This example depicts a basic chat interface where new messages are posted and immediately shown to all connected clients in real-time.
Hash: 45814ec51b2ef11a360596b591ecddbecb021b6650cdef6c4ef022c41ac3d051