Setting Up GraphQL Subscriptions and Push Notifications with Nest JS

Pragmatic Reviews
2 min readApr 30, 2020

--

Setting Up GraphQL Subscriptions and Push Notifications with Nest JS

In this video we are going to setup subscriptions and push notifications in our GraphQL Server with Nest JS.

On a previous video we created a GraphQL API from the ground up, including queries and mutations.

Another feature supported by GraphQL APIs are Subscriptions that allow a server to publish data to its clients when a specific event happens. Let’s take a look at what changes we need to make to our application in order to support GraphQL Subscriptions.

The idea for this is that every time we create a new Video using a mutation in our API, we are going to trigger a push notification.

First, we need to install a library named graphql-subscriptions that provides the PubSub class which will allow us to handle subscriptions from clients and send push notifications to them:

npm install --save graphql-subscriptions

Then we need to add a Subscription type to our initial GraphQL schema.

...type Subscription {
videoAdded(title: String!): Video
}
...

After updating the schema, we need to execute these commands to generate the classes in TypeScript:

tsc src/generate-typings.tsnode src/generate-typings.js

Once we have that new class in place we can work on the Video Service adding a ‘videoAdded‘ resolver to handle subscriptions and also publishing new events every time a new video is created within the mutation resolver.

For more details, you can watch the video below. Thanks!

GraphQL Subscriptions with NestJS

Wrapping Up

The code created for this application is available on this Gitlab repo.

You can check out the previous article of this series here.

--

--

Pragmatic Reviews

Online training on multiple technology topics such as Programming, Cloud Computing, Testing Automation, SEO and more.