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. 


    builder.Services
    .AddGraphQLServer()
    //.ConfigureSchema(sb => sb.ModifyOptions(opts => opts.StrictValidation = false))
    .AddSubscriptionType<Subscription>()
    .AddMutationType<Mutation>()
    .AddQueryType<Query>()
    .AddInMemorySubscriptions();

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)

app.UseEndpoints(endpoints =>
  {
     endpoints.MapGraphQLWebSocket("/graphql/ws");
  });



app.MapGraphQL();

app.UseWebSockets();

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. 

 public class Message
 {
     public string Sender { get; set; }
     public string Content { get; set; }
 }

This is what our subscription code looks like

public class Subscription
{
    [Subscribe]
    public Task<Message> OnMessageReceived([EventMessage] Message message)
    {
        Console.WriteLine("OnMessageReceived - received");
        return Task.FromResult(message);
    }
}

This is what our mutation looks like 

 public class Mutation
 {
     public async Task<Message> SendMessage(string name, string content,
[Service] ITopicEventSender eventSender)
     {
         var message = new Message {  Sender = name, Content = content };
         Console.WriteLine("onsend - sending message to the subscriptions");
         await eventSender.SendAsync("OnMessageReceived", message);
         return message;
     }
 }

Finally mutation type

public class Mutation
{
    public async Task<Message> SendMessage(string name, string content, [Service] ITopicEventSender eventSender)
    {
        var message = new Message {  Sender = name, Content = content };
        Console.WriteLine("onsend - sending message to the subscriptions");
        await eventSender.SendAsync("OnMessageReceived", message);
        return message;
    }
}


To test it out, run your dotnet application. The goto your browser /graphql endpoint and run the following subscription

subscription {
   onMessageReceived {
    sender
    content    
   }
}

As shown in the diagram below:-



Next, create another tab and run the following grapql. 

mutation {
   sendMessage(name: "alice", content: "ricky")
   {
      sender
      content
   }
}

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

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm