Skip to main content

Subscription

If a client wants to get notified of certain changes then a subscription is the way to go. In the background Web Sockets are used to push the update from the server to the client. This is a better alternative then for example polling, which is also easily doable with Apollo.

Subscription​

With GraphQL Yoga we can use GraphQL Subscriptions to implement this functionality. First we import PubSub and add it to our context property of our server.

import { PubSub } from 'graphql-yoga';

const pubSub = new PubSub();

Then we need to define the schema, here we define a count method that will increment a counter every second:

type Subscription {
count: Int!
}

Last we need to define the resolver:

const resolvers = {
Subscription: {
count: {
subscribe(parent, args, { pubSub }) {
let counter = 0;
setInterval(() => {
counter++;
pubSub.publish('count', { // this call could be anywhere in our application, it just happened to be here
count: counter // property must have same name as the channel
})
}, 1000);
return pubSub.asyncIterator('count'); // count is the name of the channel
}
}
}
}