Graphql subscription using type-graphql.
Being a developer it’s always cool to explore new libraries and technology.
Being fed up with REST API’s, I moved to GraphQL last year. In simple words, GraphQL is not a 100% solution for every endpoint. When it comes to webhooks, simple public routes REST API’s suits better.
So the purpose of this post is to show how to code a simple graphql subscription in typescript.
Here we’ll be using well known graphql library Apollo Graphql. For typescript compatibility, we’ll be using type-graphql.
Okay now let’s take a look at how subscription work in brief.
The above image shows the working of a subscription. It's just like a phone call one will listen and one will talk. Here client (subscriber) will be listening to any published event and the server (publisher) will publish an event whenever a certain mutation or query is hit.
Here is the folder structure.
Let’s configure the subscription resolver first.
Subscription Resolver:
Going through the above code. We create a simple query which will return Hello World on request but before returning there is an event being published called MESSAGES. Now we’ll create one more subscription query to listen for the events published. We add topics for which subscription query should listen to, in this case, its MESSAGES. This can be also an array of topics if it’s multiple.
Here is the full code.