If you’re building a modern web application, chances are you’ve heard of GraphQL. GraphQL is a query language for APIs that was developed by Facebook in 2012. It’s become increasingly popular in recent years because it allows developers to request only the data they need, which can result in faster and more efficient applications. One of the features of GraphQL is subscriptions, which allow clients to receive real-time updates from a server. In this article, we’ll show you how to use GraphQL subscriptions with WebSockets using a GraphQL WS example.
What Are GraphQL Subscriptions?
GraphQL subscriptions are a way for clients to receive real-time updates from a server. With traditional REST APIs, clients would typically need to poll the server at regular intervals to check for updates. This can be inefficient and can result in unnecessary network traffic. With GraphQL subscriptions, clients can subscribe to specific data sources and receive updates as soon as they become available.
What Are WebSockets?
WebSockets are a protocol that allows for real-time, bidirectional communication between a client and a server. With WebSockets, a client can establish a persistent connection to a server and receive updates as soon as they become available. This makes WebSockets an ideal choice for implementing real-time features like chat applications, real-time notifications, and real-time updates.
How to Use GraphQL Subscriptions with WebSockets
Step 1: Set Up a GraphQL Server
The first step in using GraphQL subscriptions with WebSockets is to set up a GraphQL server. There are many GraphQL server implementations available, but for this example, we’ll use the popular Apollo Server implementation. Here’s how to set up a basic Apollo Server instance:
- Install the necessary dependencies:
- apollo-server
- graphql
The schema defines the types and queries that are available in your GraphQL API. Here’s an example schema that defines a simple type called “Message”:
Code:
type Message {id: ID!content: String!}type Query {messages: [Message]}
type Mutation {addMessage(content: String!): Message}
type Subscription {newMessage: Message}
The resolvers define the logic for each query, mutation, and subscription defined in the schema. Here’s an example implementation of the “newMessage” subscription:
Code:
const resolvers = {Query: {messages: () => messages,},Mutation: {addMessage: (parent, { content }) => {const message = {id: messages.length + 1,content,};messages.push(message);pubsub.publish('NEW_MESSAGE', { newMessage: message });return message;},},Subscription: {newMessage: {subscribe: () => pubsub.asyncIterator(['NEW_MESSAGE']),},},};
Finally, create an instance of Apollo Server and pass in the schema and resolvers:
Code:
const server = new ApolloServer({typeDefs: schema,resolvers,});
Finally, start the server:
Code:
server.listen().then(({ url }) => {console.log(`🚀 Server ready at ${url}`);});
Step 2: Set Up a WebSocket Server
The next step is to set up a WebSocket server. There are many WebSocket server implementations available, but for this example, we’ll use the popular WebSocket implementation called ws. Here’s how to set up a basic WebSocket server:
- Install the necessary dependencies:
- Create a WebSocket server:
npm install ws
Create an instance of the WebSocket server and listen for connections:
Code:
const WebSocket = require('ws');const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {console.log('Client connected');});
Step 3: Integrate GraphQL Subscriptions with WebSockets
The final step is to integrate GraphQL subscriptions with WebSockets. To do this, we’ll use a package called graphql-ws. Here’s how to integrate GraphQL subscriptions with WebSockets:
- Install the necessary dependencies:
- Import the GraphQL server and WebSocket server:
- Create a SubscriptionServer instance:
npm install graphql-ws
Import the Apollo Server instance and the WebSocket server instance:
Code:
const { execute, subscribe } = require('graphql');const { createServer } = require('http');const { SubscriptionServer } = require('subscriptions-transport-ws');const { ApolloServer } = require('apollo-server');const { makeExecutableSchema } = require('@graphql-tools/schema');const { PubSub } = require('graphql-subscriptions');const WebSocket = require('ws');const pubsub = new PubSub();
const schema = makeExecutableSchema({typeDefs,resolvers,});
const server = new ApolloServer({schema,context: ({ req }) => {// ...},});
const wsServer = new WebSocket.Server({ port: 8080 });
Create a SubscriptionServer instance and pass in the execute and subscribe functions:
Code:
const subscriptionServer = SubscriptionServer.create({schema,execute,subscribe,onConnect: () => console.log('Client connected'),},{server: wsServer,path: '/graphql',});
Conclusion
In this article, we’ve shown you how to use GraphQL subscriptions with WebSockets using a GraphQL WS example. With GraphQL subscriptions and WebSockets, you can build real-time, efficient web applications that provide a seamless user experience. If you’re interested in learning more about GraphQL and WebSockets, be sure to check out the official documentation and other resources available online.
FAQ
What is GraphQL?
GraphQL is a query language for APIs that was developed by Facebook in 2012. It allows clients to request only the data they need, which can result in faster and more efficient applications.
What are GraphQL subscriptions?
GraphQL subscriptions are a way for clients to receive real-time updates from a server. With subscriptions, clients can subscribe to specific data sources and receive updates as soon as they become available.
What are WebSockets?
WebSockets are a protocol that allows for real-time, bidirectional communication between a client and a server. With WebSockets, a client can establish a persistent connection to a server and receive updates as soon as they become available.