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.
What are graphql-sse's main functionalities?
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);
};
Other packages similar to graphql-sse
subscriptions-transport-ws
The subscriptions-transport-ws package provides WebSocket support for GraphQL subscriptions. It is more complex than graphql-sse but offers more features and flexibility for real-time communication.
graphql-ws
The graphql-ws package is a lightweight and modern alternative to subscriptions-transport-ws for implementing GraphQL subscriptions over WebSocket. It is designed to be simple and efficient, similar to graphql-sse but using WebSocket instead of SSE.
apollo-server
Apollo Server is a popular GraphQL server implementation that supports subscriptions using WebSocket. It is a comprehensive solution for building GraphQL APIs and includes many features beyond just subscriptions.
Swiftly start with the get started guide on the website.
Short and concise code snippets for starting with common use-cases. Available on the website.
Auto-generated by TypeDoc and then rendered on the website.
Read about the exact transport intricacies used by the library in the GraphQL over Server-Sent Events Protocol document.
File a bug, contribute with code, or improve documentation? Read up on our guidelines for contributing and drive development with yarn test --watch
away!