Introduction to GraphQL Mutation through Java

Prerequisite

If you don’t know about GraphQL, this link is a good place to start. This article would assume that reader has basic knowledge of REST as well as Java.

Mutation

Drawing comparison from REST, any verb (e.g. GET, POST, PUT etc) are able to do server changes. But as convention, we use POST to make new resource and PUT for updating resource. In an almost similar fashion, any query in GraphQL can be used for server side changes, however, we set up a convention that any server side write should be done via mutations.

Extending the example in last post, we will try to write a mutation that creates a driver(i.e. stores the firstName as well as last name) of a given car Id.

Schema Change

type Mutation {
  createDriver(id: ID!, firstName: String!, lastName: String!): 
  Driver!
}

The mutation field returns an object type which in the example shown above is Driver. As in cases of query, we can ask for nested object. This is meant to ask for updated state after the mutation.

Data Provider

We have established in our last post that every field in GraphQL has a data provider associated with it. The one for this simple mutation is not different. We have added a new type for the added mutation as shown below.

.type(TypeRuntimeWiring.newTypeWiring("Mutation")
                        .dataFetcher("createDriver", graphQLDataFetchers.setDriverDataFetcher()))

The updated class should look like one below:

package com.nulpointerexception.cabdetailsgraphQLdemo;
import com.google.common.io.Resources;
import graphql.GraphQL;
import graphql.schema.GraphQLSchema;
import graphql.schema.idl.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
@Component
public class GraphQLProvider {
public static final String SCHEMA_DEFINITION = "schema.graphqls";
private GraphQL graphQL;
@Bean
public GraphQL graphQL(){
return this.graphQL;
}
@Autowired
GraphQLDataFetchers graphQLDataFetchers;
@PostConstruct
public void init() throws IOException {
URL url = Resources.getResource(SCHEMA_DEFINITION);
String sdl = Resources.toString(url, Charset.forName("UTF-8"));
GraphQLSchema graphQLSchema = buildSchema(sdl);
this.graphQL = GraphQL.newGraphQL(graphQLSchema).build();
}
private GraphQLSchema buildSchema(String sdl) {
TypeDefinitionRegistry typeDefinitionRegistry = new SchemaParser().parse(sdl);
RuntimeWiring runtimeWiring = buildWiring();
SchemaGenerator schemaGenerator = new SchemaGenerator();
return schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
}
private RuntimeWiring buildWiring() {
return RuntimeWiring.newRuntimeWiring()
.type(TypeRuntimeWiring.newTypeWiring("Query")
.dataFetcher("cabById", graphQLDataFetchers.getCabByIdDateFetcher()))
.type(TypeRuntimeWiring.newTypeWiring("Cab")
.dataFetcher("driver", graphQLDataFetchers.getDriverDataFetcher()))
.type(TypeRuntimeWiring.newTypeWiring("Mutation")
.dataFetcher("createDriver", graphQLDataFetchers.setDriverDataFetcher()))
.build();
}
}
view raw GraphQLProvider.java hosted with ❤ by GitHub

Data Fetcher

The data fetcher for the mutation field is shown in gist below. Here, we have used a in-memory data storage but this can connect to any database or call some other API as well.

public DataFetcher setDriverDataFetcher() {
return dataFetchingEnvironment > {
String carId = dataFetchingEnvironment.getArgument("id");
String firstName = dataFetchingEnvironment.getArgument("firstName");
String lastName = dataFetchingEnvironment.getArgument("lastName");
Map<String, String> driverDetails = new HashMap<>();
driverDetails.put("firstName", firstName);
driverDetails.put("lastName", lastName);
driverDetails.put("id", carId);
drivers.add(driverDetails);
return driverDetails;
};
}

Mutation Query

mutation {
  createDriver(id: "car1", firstName: "Prathamesh", lastName: "Waghmode") {
    id
    firstName
  }
}
GraphQL Playground Screenshot

Github repository

GraphQL Mutation Demo


Reference:

GraphQL Java

GraphQL Official

Apollo Blog

One thought on “Introduction to GraphQL Mutation through Java

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: