2

I am trying to implement GraphQL Subscriptions using ActionCable with graphql-ruby gem.

I figured out from this link that GraphQL channel needs to be created to which clients needs to subscribe. Normally, in ActionCable, we will stream_from required channel in the subscribed action. But, the example in the link specifies a execute method with parameter. When will this method be executed?

Also, the doc states See Apollo Client or Relay Modern for client usage. Is it a must to use any one of these or can I use coffeescript to subscribe and update UI?

1 Answers1

4

Not sure if you've solved your problem already but for anyone that has trouble understanding how GraphQL works with ActionCable. I've set up an example repository and will try update the docs to be better.

https://github.com/bidluo/GraphQL-ActionCableSubscriptions

To answer your question, execute is like any other ActionCable action when sending messages so to call it you would do the following where data contains everything and query is really the only bit of GraphQL.

{
   "command":"message",
   "identifier":"{\"channel\":\"GraphqlChannel\"}",
   "data":"{ \"query\": \"subscription { newMessage { content } }\", \"variables\": null, \"action\": \"execute\" }"
}

But you'd need to make sure you're subscribed to the channel first:

{
   "command":"subscribe",
   "identifier":"{\"channel\":\"GraphqlChannel\"}"
}
David Liaw
  • 3,193
  • 2
  • 18
  • 28
  • Hi David, this was useful but I've noticed something. Following the example, if I subscribe N different consumers to newMessage, N queries will be triggered to send exactly the same data. This is very inefficient. Did you come across the same situation? – Dario Barrionuevo Feb 10 '21 at 18:18
  • @DarioBarrionuevo hi, honestly this didn't really pan out for me so I just switched everything to using push notifications instead. Turned out a bit easier since I only needed to support push rather than both push and sockets. To answer your question though, you could modify your AC channel to cache the query rather than execute a new one. – David Liaw Mar 02 '21 at 02:42
  • I asked this to the gem developer, and duplicated queries are the expected behavior for this setup. GraphQL Broadcasts must be used instead. – Dario Barrionuevo Mar 04 '21 at 15:03