Skip to content

vertx-howtos/graphql-howto

Repository files navigation

Implementing a GraphQL server

Build Status

This document will show you how to implement a GraphQL server.

What you will build

You will build a GraphQL server to manage your personal tasks (a.k.a. the todo list).

The application consists in a few files:

  1. the tasks.graphqls schema file

  2. the Task data class

  3. the GraphQLVerticle class

What you need

  • A text editor or IDE

  • Java 17 or higher

  • Maven or Gradle

Create a project

The code of this project contains Maven and Gradle build files that are functionally equivalent.

Using Maven

Here is the content of the pom.xml file you should be using:

Using Gradle

Assuming you use Gradle with the Kotlin DSL, here is what your build.gradle.kts file should look like:

Managing tasks with Vert.x Web and GraphQL

Creating the schema

First things first, let’s create a GraphQL schema for the task management app:

The schema defines:

  • the Task type with 3 fields: id, description and completed

  • the allTasks query that returns an array of tasks and optionally takes a parameter uncompletedOnly (defaults to true)

  • the complete mutation that takes the task id as parameter and returns a boolean indicating whether the operation was successful

Implementing the server

In the application, tasks will be modeled by the Task class:

Important
The Task class field names must match those of the corresponding GraphQL schema type.

On startup, we shall create a few items:

Then the GraphQL-Java engine must be setup:

So far, so good. Now how does one implement a data fetcher?

The allTasks data fetcher gets the uncompletedOnly parameter from the DataFetchingEnvironment. Its value is either provided by the client or, as defined in the schema file, set to true.

Warning
Do not block the Vert.x event loop in your data fetchers. In this how-to, the data set is small and comes from memory, so it’s safe to implement allTasks in a blocking fashion. When working with databases, caches or web services, make sure your data fetcher returns a CompletionStage. For further details, please refer to the The Vert.x Web GraphQL Handler documentation.

The code for the complete mutation is not much different:

It gets the id parameter provided by the client, then looks up for the corresponding task. If a task is found, it is updated and the mutation returns true to indicate success.

Almost there! Now let’s put things together in the verticle start method:

Running the application

The GraphQLVerticle needs a main method:

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •