Skip to main content

Vert.x Web GraphQL extends Vert.x Web with the GraphQL-Java library so that you can build a GraphQL server.

Tip
This is the reference documentation for Vert.x Web GraphQL. It is highly recommended to get familiar with the GraphQL-Java API first. You may start by reading the GraphQL-Java documentation.
Warning
This module has Tech Preview status, this means the API can change between versions.

Getting started

To use this module, add the following to the dependencies section of your Maven POM file:

<dependency>
 <groupId>io.vertx</groupId>
 <artifactId>vertx-web-graphql</artifactId>
 <version>3.8.4</version>
</dependency>

Or, if you use Gradle:

compile 'io.vertx:vertx-web-graphql:3.8.4'

Handler setup

Create a Vert.x Web Route and a GraphQLHandler for it:

require 'vertx-web-graphql/graph_ql_handler'
graphQL = setup_graph_ql_java()

router.route("/graphql").handler(&VertxWebGraphql::GraphQLHandler.create(graphQL).method(:handle))

The handler serves both GET and POST requests. However you can restrict the service to one type of HTTP method:

require 'vertx-web-graphql/graph_ql_handler'
graphQL = setup_graph_ql_java()

router.post("/graphql").handler(&VertxWebGraphql::GraphQLHandler.create(graphQL).method(:handle))
Tip
The GraphQLHandler does not require a BodyHandler to read POST requests content.

GraphiQL client

As you are building your application, testing your GraphQL queries in GraphiQL can be handy.

To do so, create a route for GraphiQL resources and a GraphiQLHandler for them:

require 'vertx-web-graphql/graphi_ql_handler'
options = {
  'enabled' => true
}

router.route("/graphiql/*").handler(&VertxWebGraphql::GraphiQLHandler.create(options).method(:handle))
Note
The GraphiQL user interface is disabled by default for security reasons. This is why you must configure the GraphiQLHandlerOptions to enable it.
Tip
GraphiQL is enabled automatically when Vert.x Web runs in development mode. To switch the development mode on, use the VERTXWEB_ENVIRONMENT environment variable or vertxweb.environment system property and set it to dev. In this case, create the GraphiQLHandler without changing the enabled property.

If your application is protected by authentication, you can customize the headers sent by GraphiQL dynamically:

require 'vertx/multi_map'
graphiQLHandler.graphi_ql_request_headers(lambda { |rc|
  token = rc.get("token")
  return Vertx::MultiMap.case_insensitive_multi_map().add(Java::IoVertxCoreHttp::HttpHeaders::AUTHORIZATION, "Bearer #{token}")
})

router.route("/graphiql/*").handler(&graphiQLHandler.method(:handle))

Please refer to the GraphiQLHandlerOptions documentation for further details.

Enable query batching

Query batching consists in posting an array instead of a single object to the GraphQL endpoint.

Vert.x Web GraphQL can handle such requests but by default the feature is disabled. To enable it, create the GraphQLHandler with options:

require 'vertx-web-graphql/graph_ql_handler'
options = {
  'requestBatchingEnabled' => true
}

handler = VertxWebGraphql::GraphQLHandler.create(graphQL, options)

Building a GraphQL server

The GraphQL-Java API is very well suited for the asynchronous world: the asynchronous execution strategy is the default for queries (serial asynchronous for mutations).

To avoid blocking the event loop, all you have to do is implement data fetchers that return a CompletionStage instead of the result directly.

dataFetcher = lambda { |environment|

  completableFuture = Java::JavaUtilConcurrent::CompletableFuture.new()

  retrieve_links_from_backend(environment) { |ar_err,ar|
    if (ar_err == nil)
      completableFuture.complete?(ar)
    else
      completableFuture.complete_exceptionally?(ar_err)
    end
  }

  return completableFuture
}

runtimeWiring = Java::GraphqlSchemaIdl::RuntimeWiring.new_runtime_wiring().type("Query", lambda { |builder|
  builder.data_fetcher("allLinks", dataFetcher)
}).build()

Fetching data with callback-based APIs

Implementing a data fetcher that returns a CompletionStage is not a complex task. But when you work with Vert.x callback-based APIs, it requires a bit of boilerplate.

This is where the VertxDataFetcher can help:

dataFetcher = Java::IoVertxExtWebHandlerGraphql::VertxDataFetcher.new(lambda { |environment,future|

  retrieve_links_from_backend(environment, &future)

})

runtimeWiring = Java::GraphqlSchemaIdl::RuntimeWiring.new_runtime_wiring().type("Query", lambda { |builder|
  builder.data_fetcher("allLinks", dataFetcher)
}).build()

Providing data fetchers with some context

Very often, the GraphQLHandler will be declared after other route handlers. For example, you could protect your application with authentication.

In this case, it is likely that your data fetchers will need to know which user is logged-in to narrow down the results. Let’s say your authentication layer stores a User object in the RoutingContext.

You may retrieve this object by inspecting the DataFetchingEnvironment:

dataFetcher = Java::IoVertxExtWebHandlerGraphql::VertxDataFetcher.new(lambda { |environment,future|

  routingContext = environment.get_context()

  user = routingContext.get("user")

  retrieve_links_posted_by(user, &future)

})
Note
The routing context is available with any kind of data fetchers, not just VertxDataFetcher.

If you prefer not to expose the routing context to your data fetchers, configure the GraphQL handler to customize the context object:

require 'vertx-web-graphql/graph_ql_handler'
dataFetcher = Java::IoVertxExtWebHandlerGraphql::VertxDataFetcher.new(lambda { |environment,future|

  # User as custom context object
  user = environment.get_context()

  retrieve_links_posted_by(user, &future)

})

graphQL = setup_graph_ql_java(dataFetcher)

# Customize the query context object when setting up the handler
handler = VertxWebGraphql::GraphQLHandler.create(graphQL).query_context(lambda { |routingContext|

  return routingContext.get("user")

})

router.route("/graphql").handler(&handler.method(:handle))

JSON data results

The default GraphQL data fetcher is PropertyDataFetcher. As a consequence, it will be able to read the fields of your domain objects without further configuration.

Nevertheless, some Vert.x data clients return JsonArray and JsonObject results.

If you don’t need (or don’t wish to) use a domain object layer, you can configure GraphQL-Java to use VertxPropertyDataFetcher instead:

builder = Java::GraphqlSchemaIdl::RuntimeWiring.new_runtime_wiring()

builder.wiring_factory(Java::GraphqlSchemaIdl::WiringFactory.new())
Tip
VertxPropertyDataFetcher wraps a PropertyDataFetcher so you can still use it with domain objects.

Using dataloaders

Dataloaders help you to load data efficiently by batching fetch requests and caching results.

First, create a batch loader:

linksBatchLoader = lambda { |keys,environment|

  return retrieve_links_from_backend(keys, environment)

}
Tip
If you work with Vert.x callback-based APIs, you may use a VertxBatchLoader to simplify your code.

Then, configure the GraphQLHandler to create a DataLoaderRegistry for each request:

Code not translatable

You can use an Apollo WebSocketLink which connects over a websocket. This is specially useful if you want to add subscriptions to your GraphQL schema, but you can also use the websocket for queries and mutations.

require 'vertx-web-graphql/apollo_ws_handler'
graphQL = setup_graph_ql_java()

router.route("/graphql").handler(&VertxWebGraphql::ApolloWSHandler.create(graphQL).method(:handle))
Important
To support the graphql-ws websocket subprotocol, it has to be added to the server configuration:
httpServerOptions = {
  'websocketSubProtocols' => "graphql-ws"
}
vertx.create_http_server(httpServerOptions).request_handler(&router.method(:handle)).listen(8080)
Note
If you want to support a WebSocketLink and a HttpLink in the same path, you can add the ApolloWSHandler in first place and then the GraphQLHandler.
require 'vertx-web-graphql/apollo_ws_handler'
require 'vertx-web-graphql/graph_ql_handler'
graphQL = setup_graph_ql_java()

router.route("/graphql").handler(&VertxWebGraphql::ApolloWSHandler.create(graphQL).method(:handle))
router.route("/graphql").handler(&VertxWebGraphql::GraphQLHandler.create(graphQL).method(:handle))

Here you can find how to configure the Apollo SubscriptionClient: https://github.com/apollographql/subscriptions-transport-ws

Important
A subscription DataFetcher has to return a org.reactivestreams.Publisher instance.