You can make a GraphQL request with the commercetools JVM SDK as follows:
- First implement the Java class representing your GraphQL response. So if one result object looks like:
{
"name": "category name"
}
Then the implementing java class CategoryAutoCompleteResult
would look something like this:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.sphere.sdk.models.Base;
public class CategoryAutoCompleteResult extends Base {
private final String name;
@JsonCreator
public CategoryAutoCompleteResult(@JsonProperty("name") final String name) {
this.name = name;
}
public String getName() {
return name;
}
}
- Then implement the GraphQL request class
CategoryAutoCompleteRequest
. This could be simplified by just implementing the SphereRequest
interface from the commercetools JVM SDK as follows:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import io.sphere.sdk.client.HttpRequestIntent;
import io.sphere.sdk.client.SphereRequest;
import io.sphere.sdk.http.HttpMethod;
import io.sphere.sdk.http.HttpResponse;
import io.sphere.sdk.json.SphereJsonUtils;
import io.sphere.sdk.models.Base;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
public class CategoryAutoCompleteRequest extends Base implements SphereRequest<List<CategoryAutoCompleteResult>> {
private final String queryString;
CategoryAutoCompleteRequest(final String queryString) {
this.queryString = queryString;
}
public static CategoryAutoCompleteRequest of(@Nonnull final String queryString) {
return new CategoryAutoCompleteRequest(queryString);
}
@Nullable
@Override
public List<CategoryAutoCompleteResult> deserialize(final HttpResponse httpResponse) {
final JsonNode rootJsonNode = SphereJsonUtils.parse(httpResponse.getResponseBody());
final JsonNode results = rootJsonNode.get("data").get("categoryAutocomplete").get("results");
return SphereJsonUtils
.readObject(results, new TypeReference<List<CategoryAutoCompleteResult>>() {
});
}
@Override
public HttpRequestIntent httpRequestIntent() {
final String queryBody =
String.format("{categoryAutocomplete(locale: \"en\", text: \"%s\") {results{name(locale: \"en\")}}}",
queryString);
final String graphQlQuery = buildGraphQlQuery(queryBody);
return HttpRequestIntent.of(HttpMethod.POST, "/graphql", graphQlQuery);
}
private static String buildGraphQlQuery(@Nonnull final String queryBody) {
return String.format("{ \"query\": \"%s\"}", queryBody.replace("\"", "\\\""));
}
}
- Then the last step would be to execute the actual request. Assuming you already have a setup
SphereClient
. Executing the request would looks as follows:
final List<CategoryAutoCompleteResult> results = sphereClient
.execute(CategoryAutoCompleteRequest.of("myIncompleteCatName")).toCompletableFuture().join();