What is graphql-sse?
The graphql-sse package provides a way to implement GraphQL over Server-Sent Events (SSE). This allows for real-time updates and subscriptions in a GraphQL API using the SSE protocol, which is a simpler alternative to WebSockets.
Setting up a GraphQL server with SSE
This code sets up a basic GraphQL server with SSE support. It defines a schema with a query and a subscription, and starts an HTTP server that listens for GraphQL SSE requests.
const { createServer } = require('http');
const { execute, subscribe } = require('graphql');
const { makeExecutableSchema } = require('@graphql-tools/schema');
const { GraphQLSse } = require('graphql-sse');
const typeDefs = `
type Query {
hello: String
}
type Subscription {
time: String
}
`;
const resolvers = {
Query: {
hello: () => 'Hello world!',
},
Subscription: {
time: {
subscribe: async function* () {
while (true) {
yield { time: new Date().toISOString() };
await new Promise(resolve => setTimeout(resolve, 1000));
}
},
},
},
};
const schema = makeExecutableSchema({ typeDefs, resolvers });
const server = createServer(GraphQLSse({ schema, execute, subscribe }));
server.listen(4000, () => {
console.log('Server is running on http://localhost:4000/graphql');
});
Client-side subscription using EventSource
This code demonstrates how to subscribe to a GraphQL subscription using the EventSource API on the client side. It listens for messages from the server and logs the data to the console.
const eventSource = new EventSource('http://localhost:4000/graphql?query=subscription{time}');
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log(data);
};