= Vert.x Web GraphQL

Vert.x Web GraphQL extends Vert.x Web with the https://www.graphql-java.com[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 https://www.graphql-java.com/documentation/v13/[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:

[source,xml,subs="+attributes"]
----
<dependency>
 <groupId>io.vertx</groupId>
 <artifactId>vertx-web-graphql</artifactId>
 <version>3.8.0</version>
</dependency>
----

Or, if you use Gradle:

[source,groovy,subs="+attributes"]
----
compile 'io.vertx:vertx-web-graphql:3.8.0'
----

== Handler setup

Create a Vert.x Web `link:../../apidocs/io/vertx/ext/web/Route.html[Route]` and a `link:../../apidocs/io/vertx/ext/web/handler/graphql/GraphQLHandler.html[GraphQLHandler]` for it:

[source,kotlin]
----
var graphQL = setupGraphQLJava()

router.route("/graphql").handler(GraphQLHandler.create(graphQL))

----

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

[source,kotlin]
----
var graphQL = setupGraphQLJava()

router.post("/graphql").handler(GraphQLHandler.create(graphQL))

----

TIP: The `link:../../apidocs/io/vertx/ext/web/handler/graphql/GraphQLHandler.html[GraphQLHandler]` does not require a `link:../../apidocs/io/vertx/ext/web/handler/BodyHandler.html[BodyHandler]` to read `POST` requests content.

=== GraphiQL client

As you are building your application, testing your GraphQL queries in https://github.com/graphql/graphiql[GraphiQL] can be handy.

The GraphiQL user interface is disabled by default.
To enable it, configure the `link:../../apidocs/io/vertx/ext/web/handler/graphql/GraphiQLOptions.html[GraphiQLOptions]`:

[source,kotlin]
----
var options = GraphQLHandlerOptions(
  graphiQLOptions = GraphiQLOptions(
    enabled = true))

router.route("/graphql").handler(GraphQLHandler.create(graphQL, options))

----

Then browse to http://localhost:8080/graphql.

TIP: GraphiQL user interface is enabled automatically when Vert.x Web is 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`.

Please refer to the `link:../../apidocs/io/vertx/ext/web/handler/graphql/GraphiQLOptions.html[GraphiQLOptions]` documentation for details on customization options.

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

[source,kotlin]
----
var options = GraphQLHandlerOptions(
  graphiQLOptions = GraphiQLOptions(
    enabled = true))

var graphQLHandler = GraphQLHandler.create(graphQL, options).graphiQLRequestHeaders({ rc ->
  var token = rc.get<Any>("token")
  return MultiMap.caseInsensitiveMultiMap().add(io.vertx.core.http.HttpHeaders.AUTHORIZATION, "Bearer ${token}")
})

----

=== 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 `link:../../apidocs/io/vertx/ext/web/handler/graphql/GraphQLHandler.html[GraphQLHandler]` with options:

[source,kotlin]
----
var options = GraphQLHandlerOptions(
  requestBatchingEnabled = true)

var handler = 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 https://vertx.io/docs/vertx-core/java/#golden_rule[avoid blocking the event loop], all you have to do is implement https://www.graphql-java.com/documentation/v13/data-fetching/[data fetchers] that return a `CompletionStage` instead of the result directly.

[source,kotlin]
----
var dataFetcher = { environment ->

  var completableFuture = java.util.concurrent.CompletableFuture()

  retrieveLinksFromBackend(environment, { ar ->
    if (ar.succeeded()) {
      completableFuture.complete(ar.result())
    } else {
      completableFuture.completeExceptionally(ar.cause())
    }
  })

  return completableFuture
}

var runtimeWiring = graphql.schema.idl.RuntimeWiring.newRuntimeWiring().type("Query", { builder ->
  builder.dataFetcher("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 `link:../../apidocs/io/vertx/ext/web/handler/graphql/VertxDataFetcher.html[VertxDataFetcher]` can help:

[source,kotlin]
----
var dataFetcher = io.vertx.ext.web.handler.graphql.VertxDataFetcher({ environment, future ->

  retrieveLinksFromBackend(environment, future)

})

var runtimeWiring = graphql.schema.idl.RuntimeWiring.newRuntimeWiring().type("Query", { builder ->
  builder.dataFetcher("allLinks", dataFetcher)
}).build()

----

=== Providing data fetchers with some context

Very often, the `link:../../apidocs/io/vertx/ext/web/handler/graphql/GraphQLHandler.html[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 `link:../../apidocs/io/vertx/ext/web/RoutingContext.html[RoutingContext]`.

You may retrieve this object by inspecting the `DataFetchingEnvironment`:

[source,kotlin]
----
var dataFetcher = io.vertx.ext.web.handler.graphql.VertxDataFetcher({ environment, future ->

  var routingContext = environment.getContext<Any>()

  var user = routingContext.get<Any>("user")

  retrieveLinksPostedBy(user, future)

})

----

NOTE: The routing context is available with any kind of data fetchers, not just `link:../../apidocs/io/vertx/ext/web/handler/graphql/VertxDataFetcher.html[VertxDataFetcher]`.

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

[source,kotlin]
----
var dataFetcher = io.vertx.ext.web.handler.graphql.VertxDataFetcher({ environment, future ->

  // User as custom context object
  var user = environment.getContext<Any>()

  retrieveLinksPostedBy(user, future)

})

var graphQL = setupGraphQLJava(dataFetcher)

// Customize the query context object when setting up the handler
var handler = GraphQLHandler.create(graphQL).queryContext({ routingContext ->

  return routingContext.get<Any>("user")

})

router.route("/graphql").handler(handler)

----

=== 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 `link:../../apidocs/io/vertx/core/json/JsonArray.html[JsonArray]` and `link:../../apidocs/io/vertx/core/json/JsonObject.html[JsonObject]` results.

If you don't need (or don't wish to) use a domain object layer, you can configure GraphQL-Java to use `link:../../apidocs/io/vertx/ext/web/handler/graphql/VertxPropertyDataFetcher.html[VertxPropertyDataFetcher]` instead:

[source,kotlin]
----
var builder = graphql.schema.idl.RuntimeWiring.newRuntimeWiring()

builder.wiringFactory(graphql.schema.idl.WiringFactory())

----

TIP: `link:../../apidocs/io/vertx/ext/web/handler/graphql/VertxPropertyDataFetcher.html[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, you must configure the `GraphQL` object to use the `DataLoaderDispatcherInstrumentation`:

[source,kotlin]
----
var dispatcherInstrumentation = graphql.execution.instrumentation.dataloader.DataLoaderDispatcherInstrumentation()

var graphQL = graphql.GraphQL.newGraphQL(graphQLSchema).instrumentation(dispatcherInstrumentation).build()

----

Then create a batch loader:

[source,kotlin]
----
var linksBatchLoader = { keys, environment ->

  return retrieveLinksFromBackend(keys, environment)

}

----

TIP: If you work with Vert.x callback-based APIs, you may use a `link:../../apidocs/io/vertx/ext/web/handler/graphql/VertxBatchLoader.html[VertxBatchLoader]` to simplify your code.

Eventually, configure the `link:../../apidocs/io/vertx/ext/web/handler/graphql/GraphQLHandler.html[GraphQLHandler]` to create a `DataLoaderRegistry` for each request:

[source,kotlin]
----
Code not translatable
----

ifeval::["kotlin" == "java"]
include::override/rxjava2.adoc[]
endif::[]