Real-time applications are important in several instances. Especially in a scenario whereby immediate feedback is important such as messaging apps and IoT apps. Let’s imagine a case in IoT whereby a smoke detector needs to relay information to water sprinklers in a burning building. This information has to be in real-time to save the situation before it worsens.
In this blog we will cover:
- NestJS
- GraphQL Subscriptions
- Hands-on
- Conclusion
NestJS
NestJS is a well-known open-source web framework for developing scalable and efficient Node.js applications. It is intended to provide a modular and easy-to-maintain architecture, making it an excellent alternative for designing complicated applications.
NestJS is built on top of popular frameworks such as Express and TypeScript, and it includes a lot of features out of the box such as dependency injection, testing utilities, and support for several database types.
Its architecture is highly influenced by Angular, making it a familiar alternative for developers who are already familiar with the principles and design patterns of Angular.
GraphQL Subscriptions
GraphQL Subscriptions is a GraphQL API feature that allows for real-time communication between the client and the server. GraphQL Subscriptions eliminate the need for excessive polling and reduce latency by allowing the server to deliver updates to the client as soon as they become available, removing the need for needless polling and decreasing latency.
Clients can subscribe to specific data events on the server using GraphQL Subscriptions, such as the creation of a new resource or the updating of an existing one. Once subscribed, the server will deliver any relevant updates to the client in real-time. This is especially beneficial for applications that demand real-time updates, such as chat apps, social media feeds, or dashboards.
GraphQL Subscriptions are specified by a separate schema that details the many sorts of events that clients can subscribe to, as well as the data that is returned when those events occur. The server sends updates to registered clients using WebSocket connections, and clients can unsubscribe from events when they are no longer required.
From the name itself, a subscription is meant for a subscriber. In this case, it is a client of any sort – a mobile app, a web app – who has opted in to receive real-time updates based on events that are fired on the server.
Hands-On
The repository for the code used in this blog is at https://github.com/workfall/workfall-nest-graphql
Pre-requisites
First of all, you have to ensure that MongoDB is installed on your machine. Follow this link https://www.mongodb.com/docs/manual/installation/ to install your OS-compliant MongoDB. Make certain that the community edition is installed.
You should have NestJS cli installed and you can generate a new app using the command nest new <app_name>. After that, we can start by configuring MongoDB and GraphQL.
In your project folder, open the terminal and install the following npm i @nestjs/mongoose mongoose and npm i @nestjs/graphql @nestjs/apollo @apollo/server graphql.
Folder Structure
Configurations
Let us start by configuring MongoDB and GraphQL in the root module
app.module.ts:
You will notice an error because GraphQL does not have any resolvers, so you have to create at least one resolver and add it to the providers.
resolvers/user.resolver.ts:
models/user.model.ts:
Note that @InputType allows us to define user input parameters for the GraphQL schema.
main.ts:
You will notice that we have done away with all the controllers because we are not going to use any other endpoints apart from /graphql. If you run the app, you should be able to see the GraphQL playground as shown below.
Code
We can write our first query to see if it works. Always used named operations to make your development testing easier.
You will notice that GraphQL is smart enough to know which fields exist in your schema. You should also note that it generates a schema.gql file in the root of your project and this file should not be manually changed. Any time GraphQL detects a new schema or operation in the resolver, it registers the schema and any other operations such as mutations, queries, and subscriptions.
schema.gql:
collections/user.schema.ts:
database/database.module.ts:
app.module.ts:
It is most advisable to change the Mongoose root module config to use forRootAsync.
app.service.ts:
user.resolver.ts:
You should be able to perform a createUser Mutation and a getUser query as shown below:
Subscriptions
Now we need to create a real-time update each time a new user is created. We will set up a GraphQL subscription. First, we need to do a configuration to the GraphQL module to use subscriptions and also change the transport layer to web sockets instead of HTTP.
app.module.ts:
Note: Remember to install graphql-subscriptions, subscriptions-transport-ws and graphql-ws packages.
resolvers/user.resolver.ts:
In the above code, we begin by initializing a publisher at the top level. Then we create a subscription in the resolvers. In the createUser mutation, we publish the newUser event with the created user so that all subscribers receive the latest data.
The split screen below shows a publisher and a listening subscriber, once we create a new user, the subscriber receives the new data immediately.
Conclusion
In this blog, we learned how we can create a real-time backend application using GraphQL subscriptions. With the use of real-time protocols like web sockets, we can create powerful applications such as chat applications, IoT applications, and data streaming applications.
GraphQL is a powerful tool and it makes server-side evolution less painful and more fault tolerant compared to the REST architecture. We will come up with more such use cases in our upcoming blogs.
Meanwhile…
If you are a NestJS & GraphQL Enthusiast and want to explore more about the above topics, here are a few of our blogs for your reference:
- Create a No-code GraphQL Server Using Hasura and PostgreSQL
- How to upload large files (1GB and beyond) to AWS S3 using NestJS (backend) and ReactJS (frontend)?
- How to Architect NestJS Microservices with AWS Elastic Beanstalk?
- How to Deploy NestJS Microservices to AWS Elastic Beanstalk?
Stay tuned to get all the updates about our upcoming blogs on the cloud and the latest technologies.
Keep Exploring -> Keep Learning -> Keep Mastering
At Workfall, we strive to provide the best tech and pay opportunities to kickass coders around the world. If you’re looking to work with global clients, build cutting-edge products, and make big bucks doing so, give it a shot at workfall.com/partner today!