Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement subscriptions in GraphQL HotChocolate?

I am implementing HotChocolate as part of my ASP.NET API. I'm trying to add subscriptions to the chat portion on my app, however, the documentation on the HotChocolate site is not implemented yet. From what I can tell from other sites/frameworks, I can use the C# IObservable<Chat> as the return type for the subscription method.

Can anyone give me an example of a query method or point me towards another resource?

public async Task<IObservable<Message>> GetMessages(Guid chatId) {
  var messages = ..Get chats;

  return messages;
}

However, how does this work from a query standpoint? How do we trigger an event to update this?

Thanks.

like image 300
Tristan Trainer Avatar asked Jul 16 '19 09:07

Tristan Trainer


People also ask

How are GraphQL subscriptions implemented?

GraphQL uses Event-based approach to implement its subscription operation. The client subscribes for some particular events to the server. The server informs the client whenever these events trigger.

What is the difference between a GraphQL query and subscription?

Like queries, subscriptions enable you to fetch data. Unlike queries, subscriptions are long-lasting operations that can change their result over time. They can maintain an active connection to your GraphQL server (most commonly via WebSocket), enabling the server to push updates to the subscription's result.

Does GraphQL subscription use WebSocket?

Subscriptions are a GraphQL feature allowing the server to send data to its clients when a specific event happens. Subscriptions are usually implemented with WebSockets, where the server holds a steady connection to the client.

What are GraphQL subscriptions used for event based real time functionality?

GraphQL subscriptions enable publishing updates to data in real time to subscribed clients. They are invoked in response to a mutation or change in data. In other words, when data is modified via a GraphQL mutation operation, subscribed clients are automatically notified accordingly.


1 Answers

Since the original documentation link became obsolete I am posting this new link that refers to our workshop project.

Chapter 7 shows how to do subscriptions in two variants. https://github.com/ChilliCream/graphql-workshop/blob/master/docs/7-subscriptions.md

I hope that helps.

like image 194
Michael Ingmar Staib Avatar answered Oct 02 '22 14:10

Michael Ingmar Staib