HomeBack-End & DatabaseGraphQL Subscription

GraphQL Subscription

Subscription is another type of in GraphQL.

This is use real time events using websockets, you can send notification to client for events which happen on the server using web sockets.

It you are not aware what are websockets, you can find plenty of resources online.

Let’s see how to implement subscription in our code base. As an example, let’s add a subscription to notify user when a new todo is added

Let’s first look at our backend

//subscription/todo.js

export default `
type Subscription {
    todoAdded: Todo 
}
`

//resolvers/todo.js

export default {
    Subscription: {
        todoAdded: {
            subscribe: () => pubsub.asyncIterator('TODO_ADDED')
        }
    },
    Mutation: {
        addTodo: (_, { input }) => {
            let id = Math.round(Math.random(0, 1000) * 1000)
            input.id = id
            todos.push(input)
            pubsub.publish('TODO_ADDED', { postAdded: input });
            return input
        }
    }
}

We are using pubsub library to publish events. This is quite simple

  1. define a subscription
  2. setup a resolver for the subscription
  3. publish using pubsub when the event happens

https://github.com/nodeexcel/gql_tutorial/commit/9daea919d1f0e7e4d5f29813cebe46925f17d0e4

We can test this out in our playground.

When you run a subscription, it shows as Listing.. as you can see in the screenshot

Next add a todo from playground

Add Todo done
New Todo show up on the subscription automatically!

Let’s see how to do in on the frontend

The way to setup subscription is a bit complex but described in detail here https://www.apollographql.com/docs/react/advanced/subscriptions.html#subscriptions-client

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: