hotchoc graphql sample subscription code
In this session we are going to create a graphql sample app that uses mutation and subscriptions. Graphql subscriptions uses websocket to continuously 'listen' for new event when a mutation (add/delete/update) even takes place. In this example, we are using implementation first approach.
In my startup code, I initialize graphql with the following code, adding SubscriptionType and MutationType.
Next, ensure you turn on websocket by using the following code. The method MapGraphQL is a middleware that provides access to the /graphql endpoint when the application starts up - essentially access to Hotchoc grapql client UI.
There's an option to expose a custom endpoint for issuing subscription request via MapGraphQLWebsocket.
(optional)
Then proceed to work on your subscription type. First we need to create a class called Message that will be shared by our mutation and subscription to send/receive events.
This is what our subscription code looks like
This is what our mutation looks like
Finally mutation type
To test it out, run your dotnet application. The goto your browser /graphql endpoint and run the following subscription
As shown in the diagram below:-
Next, create another tab and run the following grapql.
When you hit run on the mutation tab, you will noticed the previous tab changed as well. Noticed that it is not changed to "alice22222" without us having to click anything.
The full sample code can be found here.
https://github.com/mitzenjeremywoo/hotchoc-graphql-subscription-example-simple
Comments