AppSync supports GraphQL subscriptions out of the box! We don't even have to write custom code.
All we have to do is create a Subscription type in our GraphQL schema with @aws_subscribe()
, and pass that the mutation we want to subscribe to.
Tomasz Łakomy: [0:00] Suppose we would like to be notified as soon as someone updates a book in our API. Luckily, AppSync supports GraphQL subscriptions out of the box which allows us to use WebSockets to achieve this exact behavior.
[0:12] In order to do that, we need to add a type Subscription. We would like to be notified whenever updateBook() is triggered. We're going to do onUpdateBook. It should return a book. In order to enable subscriptions in AppSync, we have to use a special directive.
[0:28] This directive is @aws_subscribe. We have to pass in a list of all the mutations that we want to subscribe to. In our case, this is mutations equals updateBook. That's it.
[0:40] With that in place, let us test that. We can run cdk deploy. Note that we don't have to write any custom code. AppSync is going to take care of the subscription for us. The easiest way to test our newly defined subscription is to go to AWS console, to AppSync. I'm going to click on Queries.
[0:57] Here in this drop-down, I'm going to select Subscription and click on the plus sign. We only have one subscription defined. I would like to get all of those fields whenever a book is updated.
[1:08] I'm going to hit play. Now, we can see that we are subscribed to this updateBook mutation over a WebSocket. I can go back to my GraphQL client and change the rating of this book to 10. We can see that without sending any additional requests, we did receive a subscription with an updated rating of this book.
[1:25] Let me update the title. I'm going to change the title to "This Book is Awesome." Let me send that and go back over here. We can see again, the title was updated. Thanks to the GraphQL subscription, we are notified as soon as it happens.