In the previous post we set up our server using google-sign-in as identity server and we restricted access to the authenticated users. Today we’ll add real-time update thanks to GraphQL subscriptions.
The scenario we’ll implement is quite easy: we want to see in real-time when a new post is added to our list.
The first thing to do is to define the schema of our database creating the file
posts.ts with author and comment:
After that we need to create the GraphQL schema
post.schema.ts:
We defined:
– a query to retrieve all the posts (line 11);
– a mutation to store a new post (line 14).
The resolver that implements all the functionalities
post.resolver.ts:
The controller “
post.controller.ts” that will interact with our mongoDb:
Our setup is completed and it’s time to add real-time data. Apollo Server 2.0 supports GraphQL subscriptions without additional configuration or packages.
In the
post.schema.ts:
We added
line 20-22 where we expect to receive all the new posts that are added and the related controller
post.controller.ts that will interact with our mongoDB:
We added:
– line 19 to publish the new change;
– line 7-11 to add the subscription.
One small thing that makes me struggle quite a lot is the
server.ts. In case you have defined a context remember to add:
As you can see Apollo Server 2.0 allows realtime data without invasive changes to existing code. For a full working example please have a look to this repo.
@Update
I’m proud to say that I wrote as well the documentation for subscriptions in the official doc of apollo and the repo I’ve create is linked there too!
If you enjoyed this post follow me on twitter @DZurico
The post Apollo server 2.0 – real time data with subscriptions appeared first on Angular and Javascript blog.