Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable DataFetchingEnvironment as part of @GraphQLApi @Query methods #3204

Merged
merged 8 commits into from
Jul 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2020 Oracle and/or its affiliates.
* Copyright (c) 2020, 2021 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2020 Oracle and/or its affiliates.
* Copyright (c) 2020, 2021 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2020 Oracle and/or its affiliates.
* Copyright (c) 2020, 2021 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.NumberFormat;
Expand Down Expand Up @@ -120,28 +121,37 @@ static <V> DataFetcher<V> newMethodDataFetcher(Schema schema, Class<?> clazz, Me
}
}

if (args.length > 0) {
ExecutionContext executionContext;
// check for a single DataFetchingEnvironment parameter as args will be zero
Parameter[] parameters = method.getParameters();
if (parameters.length == 1 && parameters[0].getType().equals(DataFetchingEnvironment.class)) {
listArgumentValues.add(environment);
} else if (args.length > 0) {
for (SchemaArgument argument : args) {
// ensure a Map is not used as an input type
Class<?> originalType = argument.originalType();
if (originalType != null && Map.class.isAssignableFrom(originalType)) {
ensureRuntimeException(LOGGER, MAP_MESSAGE);
}
if (argument.isDataFetchingEnvironment()) {
listArgumentValues.add(environment);
} else {
// ensure a Map is not used as an input type
Class<?> originalType = argument.originalType();
if (originalType != null && Map.class.isAssignableFrom(originalType)) {
ensureRuntimeException(LOGGER, MAP_MESSAGE);
}

if (argument.isArrayReturnType() && argument.arrayLevels() > 1
&& SchemaGeneratorHelper.isPrimitiveArray(argument.originalType())) {
throw new GraphQlConfigurationException("This implementation does not currently support "
+ "multi-level primitive arrays as arguments. Please use "
+ "List or Collection of Object equivalent. E.g. "
+ "In place of method(int [][] value) use "
+ " method(List<List<Integer>> value)");
}
if (argument.isArrayReturnType() && argument.arrayLevels() > 1
&& SchemaGeneratorHelper.isPrimitiveArray(argument.originalType())) {
throw new GraphQlConfigurationException("This implementation does not currently support "
+ "multi-level primitive arrays as arguments. Please use "
+ "List or Collection of Object equivalent. E.g. "
+ "In place of method(int [][] value) use "
+ " method(List<List<Integer>> value)");
}

listArgumentValues.add(generateArgumentValue(schema, argument.argumentType(),
argument.originalType(),
argument.originalArrayType(),
environment.getArgument(argument.argumentName()),
argument.format()));
listArgumentValues.add(generateArgumentValue(schema, argument.argumentType(),
argument.originalType(),
argument.originalArrayType(),
environment.getArgument(argument.argumentName()),
argument.format()));
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import java.util.Arrays;
import java.util.Objects;

import graphql.schema.DataFetchingEnvironment;

/**
* The representation of a GraphQL Argument or Parameter.
*/
Expand Down Expand Up @@ -78,6 +80,11 @@ class SchemaArgument extends AbstractDescriptiveElement implements ElementGenera
*/
private Class<?> originalArrayType;

/**
* Indicates if the argument type is the {@link DataFetchingEnvironment} and must be ignored in schema generation.
*/
private boolean isDataFetchingEnvironment;

/**
* Construct a {@link SchemaArgument}.
*
Expand All @@ -95,6 +102,7 @@ private SchemaArgument(Builder builder) {
this.arrayLevels = builder.arrayLevels;
this.isArrayReturnTypeMandatory = builder.isArrayReturnTypeMandatory;
this.originalArrayType = builder.originalArrayType;
this.isDataFetchingEnvironment = builder.isDataFetchingEnvironment;
description(builder.description);
}

Expand Down Expand Up @@ -299,6 +307,15 @@ public void arrayReturnTypeMandatory(boolean arrayReturnTypeMandatory) {
isArrayReturnTypeMandatory = arrayReturnTypeMandatory;
}

/**
* Indicates if the argument type is the {@link DataFetchingEnvironment} and must be ignored in schema generation.
*
* @return true if the argument type is the {@link DataFetchingEnvironment}
*/
public boolean isDataFetchingEnvironment() {
return isDataFetchingEnvironment;
}

/**
* Sets the original array type.
*
Expand Down Expand Up @@ -329,6 +346,7 @@ public String toString() {
+ ", isReturnTypeMandatory=" + isArrayReturnTypeMandatory
+ ", isArrayReturnType=" + isArrayReturnType
+ ", originalArrayType=" + originalArrayType
+ ", isDataFetchingEnvironment=" + isDataFetchingEnvironment
+ ", arrayLevels=" + arrayLevels
+ ", format=" + Arrays.toString(format)
+ ", description='" + description() + '\'' + '}';
Expand All @@ -353,13 +371,14 @@ public boolean equals(Object o) {
&& Arrays.equals(format, schemaArgument.format)
&& Objects.equals(sourceArgument, schemaArgument.sourceArgument)
&& Objects.equals(originalArrayType, schemaArgument.originalArrayType)
&& Objects.equals(isDataFetchingEnvironment, schemaArgument.isDataFetchingEnvironment)
&& Objects.equals(description(), schemaArgument.description())
&& Objects.equals(defaultValue, schemaArgument.defaultValue);
}

@Override
public int hashCode() {
return Objects.hash(super.hashCode(), argumentName, argumentType, sourceArgument,
return Objects.hash(super.hashCode(), argumentName, argumentType, sourceArgument, isDataFetchingEnvironment,
isMandatory, defaultValue, description(), originalType, format, originalArrayType);
}

Expand All @@ -380,6 +399,7 @@ public static class Builder implements io.helidon.common.Builder<SchemaArgument>
private int arrayLevels;
private boolean isArrayReturnTypeMandatory;
private Class<?> originalArrayType;
private boolean isDataFetchingEnvironment;

/**
* Set the argument name.
Expand Down Expand Up @@ -506,14 +526,26 @@ public Builder arrayReturnTypeMandatory(boolean isArrayReturnTypeMandatory) {

/**
* Set the original array inner type if it is array type.
* @param originalArrayType the original array inner type if it is array type
*
* @param originalArrayType the original array inner type if it is array type
* @return updated builder instance
*/
public Builder originalArrayType(Class<?> originalArrayType) {
this.originalArrayType = originalArrayType;
return this;
}

/**
* Set if the argument type is the {@link DataFetchingEnvironment} and must be ignored in schema generation.
*
* @param isDataFetchingEnvironment if the argument type is the {@link DataFetchingEnvironment}
* @return updated builder instance
*/
public Builder dataFetchingEnvironment(boolean isDataFetchingEnvironment) {
this.isDataFetchingEnvironment = isDataFetchingEnvironment;
return this;
}

/**
* Build the instance from this builder.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,15 @@ public String getSchemaAsString() {
StringBuilder sb = new StringBuilder(getSchemaElementDescription(format()))
.append(name());

if (listSchemaArguments.size() > 0) {
// determine if there are any arguments that are DataFetcherEnvironment as they should
// not be included as standard types
boolean hasSchemaArguments = listSchemaArguments.stream().anyMatch(a -> !a.isDataFetchingEnvironment());

if (hasSchemaArguments) {
sb.append(OPEN_PARENTHESES)
.append(NEWLINE)
.append(listSchemaArguments.stream()
.filter(a -> !a.isDataFetchingEnvironment())
.map(SchemaArgument::getSchemaAsString)
.collect(Collectors.joining(COMMA_SPACE + NEWLINE)));
sb.append(NEWLINE).append(CLOSE_PARENTHESES);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@

import graphql.schema.DataFetcher;
import graphql.schema.DataFetcherFactories;
import graphql.schema.DataFetchingEnvironment;
import graphql.schema.GraphQLScalarType;
import graphql.schema.PropertyDataFetcher;
import org.eclipse.microprofile.graphql.Description;
Expand Down Expand Up @@ -515,11 +516,9 @@ private void processGraphQLApiAnnotations(SchemaType rootQueryType,
Class<?> clazz)
throws IntrospectionException, ClassNotFoundException {

for (Map.Entry<String, DiscoveredMethod> entry
: retrieveAllAnnotatedBeanMethods(clazz).entrySet()) {
for (Map.Entry<String, DiscoveredMethod> entry : retrieveAllAnnotatedBeanMethods(clazz).entrySet()) {
DiscoveredMethod discoveredMethod = entry.getValue();
Method method = discoveredMethod.method();

SchemaFieldDefinition fd = null;

// only include discovered methods in the original type where either the source is null
Expand Down Expand Up @@ -552,7 +551,7 @@ private void processGraphQLApiAnnotations(SchemaType rootQueryType,
a.argumentType(typeName);
String returnType = a.argumentType();

if (originalTypeName.equals(returnType) && !ID.equals(returnType)) {
if (originalTypeName.equals(returnType) && !ID.equals(returnType) && !a.isDataFetchingEnvironment()) {
// type name has not changed, so this must be either a Scalar, Enum or a Type
// Note: Interfaces are not currently supported as InputTypes in 1.0 of the Specification
// if is Scalar or enum then add to unresolved types and they will be dealt with
Expand Down Expand Up @@ -1244,6 +1243,7 @@ private void processMethodParameters(Method method, DiscoveredMethod discoveredM
.defaultValue(argumentDefaultValue)
.originalType(paramType)
.description(getDescription(parameter.getAnnotation(Description.class)))
.dataFetchingEnvironment(paramType.equals(DataFetchingEnvironment.class))
.build();

String[] argumentFormat = getFormattingAnnotation(parameter);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,17 @@ public void testSchemaGenerationWithArrays() {
assertThat(schemaArgument.getSchemaAsString(), is("name: [String!]"));
}

@Test
public void testSchemaArgumentGenerationWithDataFetchingEnvironment() {
SchemaArgument schemaArgument = SchemaArgument.builder()
.argumentName("test")
.dataFetchingEnvironment(true)
.argumentType("String")
.build();

assertThat(schemaArgument.isDataFetchingEnvironment(), is(true));
}

@Test
public void testSchemaGeneration() {
SchemaArgument schemaArgument = SchemaArgument.builder()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright (c) 2020, 2021 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.helidon.microprofile.graphql.server.test.queries;

import graphql.schema.DataFetchingEnvironment;

import javax.enterprise.context.ApplicationScoped;

import org.eclipse.microprofile.graphql.GraphQLApi;
import org.eclipse.microprofile.graphql.Name;
import org.eclipse.microprofile.graphql.Query;

/**
* Class that holds queries and mutations using {@link DataFetchingEnvironment}.
*/
@GraphQLApi
@ApplicationScoped
public class DataFetchingEnvironmentQueriesAndMutations {

public DataFetchingEnvironmentQueriesAndMutations() {
}

@Query
public String testNoArgs(DataFetchingEnvironment env) {
return env.getField().getName();
}

@Query
public String testWithArgs(@Name("name") String name, DataFetchingEnvironment env) {
return name + env.getField().getName();
}

@Query
public String testWithArgs2(@Name("name1") String name1, DataFetchingEnvironment env, @Name("name2") String name2) {
return name1 + name2 + env.getField().getName();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* Copyright (c) 2020, 2021 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.helidon.microprofile.graphql.server;

import java.util.Map;

import javax.inject.Inject;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;

import io.helidon.graphql.server.InvocationHandler;
import io.helidon.microprofile.graphql.server.test.queries.DataFetchingEnvironmentQueriesAndMutations;
import io.helidon.microprofile.tests.junit5.AddBean;

import org.junit.jupiter.api.Test;

/**
* Tests for {@link graphql.schema.DataFetchingEnvironment} injection.
*/
@AddBean(DataFetchingEnvironmentQueriesAndMutations.class)
class DataFetchingEnvironmentIT extends AbstractGraphQlCdiIT {

@Inject
DataFetchingEnvironmentIT(GraphQlCdiExtension graphQlCdiExtension) {
super(graphQlCdiExtension);
}

@Test
@SuppressWarnings("unchecked")
public void testWithNoArgs() throws Exception {
setupIndex(indexFileName, DataFetchingEnvironmentQueriesAndMutations.class);
InvocationHandler executionContext = createInvocationHandler();
String query = "query { testNoArgs }";
Map<String, Object> mapResults = getAndAssertResult(executionContext.execute(query));
assertThat(mapResults, is(notNullValue()));
String results = (String) mapResults.get("testNoArgs");
assertThat(results, is("testNoArgs"));
}

@Test
@SuppressWarnings("unchecked")
public void testWithArgs() throws Exception {
setupIndex(indexFileName, DataFetchingEnvironmentQueriesAndMutations.class);
InvocationHandler executionContext = createInvocationHandler();

String query = "query { testWithArgs(name: \"Tim\") }";
Map<String, Object> mapResults = getAndAssertResult(executionContext.execute(query));
assertThat(mapResults, is(notNullValue()));
String results = (String) mapResults.get("testWithArgs");
assertThat(results, is("Tim" + "testWithArgs"));
}

@Test
@SuppressWarnings("unchecked")
public void testWithArgs2() throws Exception {
setupIndex(indexFileName, DataFetchingEnvironmentQueriesAndMutations.class);
InvocationHandler executionContext = createInvocationHandler();

String query = "query { testWithArgs2(name1: \"Tim\", name2: \"Tim\") }";
Map<String, Object> mapResults = getAndAssertResult(executionContext.execute(query));
assertThat(mapResults, is(notNullValue()));
String results = (String) mapResults.get("testWithArgs2");
assertThat(results, is("TimTim" + "testWithArgs2" ));
}
}