Skip to content

server_subscription

etienne-sf edited this page Jun 22, 2024 · 19 revisions

Subscription in server mode

The server mode helps to create Java GraphQL server-side application, as explained in the server page.

The graphql-java project documents how to create subscription, in its subscription doc. But once you've read that, there is a journey left to have a working implementation of a Subscription.

The plugin hides all its complexity to you. This page is based on one of the samples provided in the project.

Starting from v1.13, queries, mutations and subscriptions can be server from the same URL.

Sample explanation

On server side, the subscription request is received as queries or mutations: you just have to implement the DataFetchersDelegateSubscription interface (if Subscription is the name of your GraphQL subscription, in your GraphQL schema). It's a Data Fetcher like the others.

With a little difference, still: it returns a [org.reactivestreams.Publisher](https://www.reactive-streams.org/reactive-streams-1.0.1-javadoc/org/reactivestreams/Publisher.html). This interface is the main item for reactive programming in Java. It's them up to your code, to feed this flux by the needed data, for this subscription.

You'll find below a description of what's done in the provided Forum sample.

Explanation, based on the Forum sample

You'll find below an explanation of the Forum server sample. This sample is available in both the maven and the plugin, as both a sample, and the server part for integration tests. You can check the Java code on github on on this page.

This Subscription server sample does this:

  • A Reactive Subject is created at startup, as a Spring Bean.
    • You'll find information on Reactive Subject here
  • Every post creation is notified to the onNext(Post) method of this Subject.
    • The post creations are implemented in the relevant mutation Data Fetcher, available on github. Take a look at the end of the createPost method: postPublisher.onNext(newPost);
    • So the Reactive Subject is notified for each post creation
  • When a subscribeToNewPost subscription arrives, the subscription datafetcher returns a new Publisher from this subject.
    • You can check the Data Fetcher code for this subscription on this page.
    • This new Publisher will automagicaly receive each newly created post, as it is created from the Subject that receives the new Post, from the mutation Data Fetecher (see above).
    • Then graphql-java will transmit on the Web Socket that has been created, when the subscription was submitted.
Clone this wiki locally