Supscriptions
Subscriptions allow clients to receive updates in real time from the server. It works by exposing a Websocket endpoint allowing real-time communication.
This documentation might use some vocabulary you never had to deal with before:
Subscription:
A subscription is a way to listen to real time events. In our case the clients will subscribe
to events coming from our backend.
Topic:
A topic (also called channel) is an identifier used to subscribe to specific events. For
example clients that will subscribe to the topic recipe:created
will only receive the events after
a recipe has been created.
PubSub:
A PubSub system is a way to Publish
and Subscribe
to different topics. For example you
could use pubsub.subscribe('recipe:created', callback)
to subscribe to the recipe:created
topic
and pubsub.publish('recipe:created', recipe)
to publish a created recipe.
You can find more information about Middlewares on the Official TypeGraphQL documentation
Configuration
First you will need to install the @graphql-yoga/subscription
package.
PubSub instance
Let's now create a new PubSub
instance that will be used by our GraphQL server to Subscribe and us to Publish.
Register it in your GraphQL configuration:
In production, you might have multiple instances of your Adonis Application running behind a Load Balancer. Events published on one instance will not be broadcasted to other instances. Please check Distributed PubSub documentation.
Typing the PubSub
Our PubSub
can already be used as it is but to have proper autocompletion and ensure we always forward proper data it is useful to define what are the different topics.
Creating Subscriptions
Subscription resolvers are similar to queries and mutation resolvers. In this example we will allow clients to receive real-time updates every time a new Recipe is created.
In a Resolver class, create a new method decorated with @Subscription
.
Single Topic
Multiple Topics
The topics
option accepts a list of topics allowing you to subscribe to multiple topics.
Dynamic Topics
The topics option also accept a function that receive the context allowing you to dynamically subscribe to topics.
Triggering Subscription Topics
Now that we have create our subscriptions, we can use the PubSub
system to broadcast our events. This will usually be done inside a mutation but you can use it wherever you want inside your application.
Inside a resolver
Outside a resolver
Distributed PubSub
When running multiple instances of your Adonis Application in a distributed environment you need a way to distribute the published event so every subscription will receive them.
This feature is not officially supported. In a near future you will be able to use your already configured Adonis Redis.
More information on the official Yoga documentation.