A GraphQL field is a named element of a GraphQL type that specifies a fetchable value and its type. Clients select fields explicitly when executing GraphQL operations. In a Java model, fields commonly correspond between the GraphQL type and its Java class. section 4.4
Fields become part of an application API through model and service design:
- The Car model defines fields for id, licensePlateNumber, manufacturer, and model; matching names allow corresponding GraphQL fields to align across services. section 4.5.1
- A GraphQL service exposes fields through operations: cars queries the fleet, while register and remove mutations change it. section 4.5.1
- The returned field values can come from in-memory structures, while GraphQL remains independent of the underlying data source. section 4.4
Listing 4.20 The GraphQLInventoryService exposes the fleet over GraphQL
package org.acme.inventory.service;
import org.acme.inventory.database.CarInventory;
import org.acme.inventory.model.Car;
import org.eclipse.microprofile.graphql.GraphQLApi;
import org.eclipse.microprofile.graphql.Mutation;
import org.eclipse.microprofile.graphql.Query;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Optional;
@GraphQLApi
public class GraphQLInventoryService {
@Inject
CarInventory inventory;
@Query
public List<Car> cars() {
return inventory.getCars();
}
@Mutation
public Car register(Car car) {
car.id = CarInventory.ids.incrementAndGet();
inventory.getCars().add(car);
return car;
}
@Mutation
public boolean remove(String licensePlateNumber) {
List<Car> cars = inventory.getCars();
Optional<Car> toBeRemoved = cars.stream()
.filter(car -> car.licensePlateNumber
.equals(licensePlateNumber))
.findAny();
if(toBeRemoved.isPresent()) {
return cars.remove(toBeRemoved.get());
} else {
return false;
}
}
}
Inspect the annotated Java service that exposes the cars field and mutation-backed inventory operations. section 4.5.1
