4

How to implement Subscription feature of GraphQL using Graphql SPQR library?

kaqqao
  • 12,984
  • 10
  • 64
  • 118
S. Das
  • 93
  • 2
  • 10

1 Answers1

5

In general terms, you just have to annotate a method with @GraphQLSubscription and make sure the method returns a org.reactivestreams.Publisher. E.g.

@GraphQLSubscription
public Publisher<Issue> issueStatusChanged(String code) {
    return ...;
}

But in practice that doesn't help you much, unless you already know how to get a Publisher.

As of Java 9, you have the Flow API at your disposal, and using org.reactivestreams.FlowAdapters#toPublisher, you can convert a Flow.Publisher to a org.reactivestreams.Publisher. Still, JDK has only one built-in publisher, SubmissionPublisher and it's probably not what you need.

Instead, it is by far the easiest to use a compliant library, like RxJava or Spring Reactor. The types they work with are either directly instances of org.reactivestreams.Publisher or are very easily convertible.

For an example using RxJava, you can see this demo project from graphql-java. Or this test from SPQR. But, both of these are too simplistic to be realistically usable.

For a more realistic example, see this demo from SPQR Spring Boot Starter project. It is using Spring Reactor, which you can use whether you're using Spring or not. That example publishes an update every time a relevant mutation runs.

Now, making a Publisher is only half the problem. You need to have a way to send the updates to the client. Furthermore, the client and the server need to agree on the protocol they'll use to exchange the messages (the new results, any encountered errors and also the control messages). Currently, only one widely used protocol exists - Apollo graphql-ws protocol. It is based on WebSockets.

SPQR Spring Boot Starter, from version 0.0.3, implements this protocol, so that it can be used with Apollo client out of the box. Other compliant clients, e.g. GraphQL Playground can naturally also be used.

Even if you don't want to use SPQR Spring Boot Starter or Spring at all, you can still learn how to implement the server from the examples there. As for for the client side, any Apollo tutorial will get you going. You can use GraphQL Playground during testing and development (GraphiQL has no support for subscriptions at this moment).

kaqqao
  • 12,984
  • 10
  • 64
  • 118
  • Thanks for your reply. My next steps are clear now. I am actually using Spring Boot. That is my preferred framework. – S. Das Jul 06 '18 at 15:59
  • @kaqqao could you please provide any documentation or help to implement the new Apollo subscription protocol, graphql-ws. thanks! – kamboj Mar 22 '22 at 19:34