GraphQL

Introduction to GraphQL Subscription & Realtime Updates

January 25, 2018

author:

Introduction to GraphQL Subscription & Realtime Updates

One of the requirements in demand in today’s application is to meet the needs of fetching realtime updates from the server. In such cases, an application needs to have a realtime connection with the server which can instantly notify the client about the triggered events. GraphQL subscriptions are used to meet such requirements.

A client typically subscribes to an event. It will process and maintain a steady ongoing connection with the server. The server then pushes the respective data back to the client when that specific event actually occurs. Thus subscriptions represent a stream of data sent to client via persistent connection while GraphQL queries and mutations follow old school request-response-cycle.

# GraphQL Subscription Setup

As you would have guessed by now, GraphQL follows a similar syntactical pattern to define all its types. Let us try and subscribe to the events of Author type:

subscription {
  newAuthor {
    name
    email
  }
}

Once the client sends the above subscription request to the server, a connection is established between them. Thus, as and when a new mutation is performed to create new Author, it responds with the details of this Author to the requesting client.

{
  "newAuthor": {
    "name": "Khushi",
    "email": "khushi@hashvel.com"
  }
}

# Subscription Schema Setup

In order to let the server know about our intention to listen to an event on a particular operation or type, we need to wire its GraphQL schema in back-end:

type Subscription {
  newAuthor: Author!
}

The final schema after defining GraphQL Query, Mutations and Subscription looks like:

type Query {
 getPosts: [Post!]!
}

type Mutation {
  createAuthor(name: String!, email:  String!): Author!
}

type Subscription {
 newAuthor: Author!
}

type Author { 
 id: ID!
 name: String!
 email: String!
 posts: [Post!]!
}

type Post {
 title: String!
 body: String!
 author: Author!
}

Conclusion:

We just completed learning one of the popular features of GraphQL – the subscriptions. It enables realtime updates in the application. We created a subscriptions as well and ended up adding it to the GraphQL Schema.

Leave a comment

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