Add support for subscriptions
We will use RedisPubSub from graphql-redis-subscriptions to publish to subscription topics. We will publish a message when the user invokes the scheduleJob mutation. A new CRON will be registered that will execute every minute. This is done so that "an automated" message is published to the notifications topic every minute.
Let's start by installing all the dependencies.
Install the necessary packages
These are the required packages
Create a new file
Copy the snippet below into the pubsub.js
Create a subscription topic.
Add the following snippet in the utils/constants.js file
Create the subscription file
Copy the following snippet
Make the following changes in the server/index.js
- Handle CORS error thrown by studio.apollographql
- Create a subscription server that will expose a websocket on the same pathname as the mutations and queries.
Click documentation tab on the top left pane header and filter by subscription → notifications and you will see the newly added subscription.
Copy the snippet below in the server/utils/queues.js
This will add support to publish to the newly created notifications topic when the scheduleJob mutation is invoked.
Copy the snippet below in the server/gql/custom/scheduleJobMutation.js
This will create a CRON that runs every minutes and publishes a message to the notifications topic.
Time to test out your subscription! Go to https://studio.apollographql.com/sandbox/explorer. Paste the snippet below in the left top pane
Hit the Play button and you will see a subscription tab pop-up in the bottom right
Paste the snippet below in the left pane
Paste the snippet below in the variables pane
Select ScheduleJob and hit the play button
Very soon you'll see another message come up in the subscriptions tab because of the EVERY_MINUTE CRON
Commit your code using the following git commands
Liked what you read? There's more where that came from! Satisfy your craving for all things digital product strategy on LeadReads. Round out your perspective with exclusive stories straight from C-suite thought leaders.
Where to go from here
You can find the complete code here: https://github.com/wednesday-solutions/node-express-batch-jobs
I would recommend going through the articles below
If this series piqued your interest please stay tuned for the next tutorial in which we will write a CD pipeline to deploy this application using ECS.
I hope you enjoyed reading this series on how to create container-aware CRONS, scheduled jobs, and GraphQL Subscriptions. If you have any questions or comments, please join the forum discussion on Twitter.