PubSub is a class that exposes a simple
It sits between your application’s logic and the GraphQL subscriptions engine - it receives a publish command from your app logic and pushing it to your GraphQL execution engine.
graphql-subscriptions exposes a default
PubSub class you can use for a simple usage of data publication.
PubSub implmentation also includes an mechanism that converts a specific
PubSub event into a stream of
AsyncIterator, which you can use with
graphql subscriptions resolver.
Check out how to change the
PubSubmechanism to an external one here
To get started, install
PubSub instance for publishing new data over your subscriptions transport, for example:
At this point, nothing works yet because there is nothing to publish into
SubscriptionsServer will manage the WebSocket connection between the GraphQL engine and the clients.
We will use the server provided by the
subscriptions-transport-ws transport package.
First install the
SubscriptionsServer expect a
subscribe (optional) and a http server:
To connect the published event from our
PubSub to GraphQL engine, we need to create
AsyncIterable and use it in the GraphQL subscription resolver definition.
Sometimes a client will want filter out specific events based on context and arguments.
To do so, we can use
withFilter helper from this package, which wraps
AsyncItrator with a filter function, and let you control each publication for each user.
Let’s see an example - for the
commentAdded server-side subscription, the client want to subscribe only to comments added to a specific repo:
withFilter, provide a filter function, which executed with the payload (the published value), variables, context and operation info, and it must return boolean or Promise
Here is the following definition of the subscription resolver, with
withFilter that will filter out all of the
commentAdded events that are not the requested repository: