Subscription is a third kind of GraphQL operation, next to Query and Mutation. Think of it as an event emitter where events are emitted by your backend and consumed by a GraphQL client - frontend in most scenarios.
GraphQL is just a specification and Express GraphQL or Apollo Server are Node implementations of the server-side part of GraphQL. Natural fit for Subscriptions is WebSocket protocol but it could be anything. We're going to focus only on WS and use
subscriptions-transport-ws package as our transport layer.
For Queries and Mutations we use
createExecution() method to create an execution logic, in case of Subscriptions it's very similar. We construct subscription phase with
createSubscription() method and provide it to a GraphQL server.
createSubscription()accepts an object with
subscribeproperty in case you want to use your own subscription logic. It uses
Why do we need it? GraphQL Modules needs to understand the life cycle of a subscription to avoid memory leaks.
We recommend to use
graphql-subscriptions as it provides handful utility functions (filtering for example) and an event emitter.
PubSub with an instance as the value so as a singleton service it becomes available across all modules.
PubSub in a module can be done both, in a resolve function and
Take a look at two things here, how
MESSAGE_ADDED event was emitter in
Messages.send() and how
Subscriptions.messageAdded subscribes to events.
Here are reference implementations of using GraphQL Subscriptions with WebSockets in both, Apollo Server and Express GraphQL.
- Apollo Server
- Express GraphQL