You will build a GraphQL server to manage your personal tasks (a.k.a. the todo list).
The application consists in a few files:
-
the
tasks.graphqlsschema file -
the
Taskdata class -
the
GraphQLVerticleclass
The code of this project contains Maven and Gradle build files that are functionally equivalent.
Assuming you use Gradle with the Kotlin DSL, here is what your build.gradle.kts file should look like:
First things first, let’s create a GraphQL schema for the task management app:
The schema defines:
-
the
Tasktype with 3 fields:id,descriptionandcompleted -
the
allTasksquery that returns an array of tasks and optionally takes a parameteruncompletedOnly(defaults totrue) -
the
completemutation that takes the taskidas parameter and returns a boolean indicating whether the operation was successful
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:
The GraphQLVerticle needs a main method: