Skip to content
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
9 changes: 8 additions & 1 deletion src/main/java/graphql/execution/ExecutionStrategy.java
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,14 @@ protected Object unboxPossibleOptional(Object result) {
return result;
}

private Iterable<Object> toIterable(Object result) {
/**
* Converts an object that is known to should be an Iterable into one
*
* @return an Iterable from that object
*
* @throws java.lang.ClassCastException if its not an Iterable
*/
protected Iterable<Object> toIterable(Object result) {
if (result.getClass().isArray()) {
return IntStream.range(0, Array.getLength(result))
.mapToObj(i -> Array.get(result, i))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import graphql.schema.GraphQLType;
import graphql.schema.GraphQLUnionType;

import java.lang.reflect.Array;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
Expand All @@ -48,11 +49,13 @@
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.function.BiFunction;
import java.util.stream.IntStream;

import static graphql.execution.ExecutionTypeInfo.newTypeInfo;
import static graphql.execution.FieldCollectorParameters.newParameters;
import static graphql.schema.DataFetchingEnvironmentBuilder.newDataFetchingEnvironment;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;

/**
* Execution Strategy that minimizes calls to the data fetcher when used in conjunction with {@link DataFetcher}s that have
Expand Down Expand Up @@ -232,7 +235,7 @@ private List<ExecutionNode> handleList(ExecutionContext executionContext, Map<St
}

MapOrList listResult = mapOrList.createAndPutList(fieldName);
for (Object rawValue : (List<Object>) value.getValue()) {
for (Object rawValue : toIterable(value.getValue())) {
rawValue = unboxPossibleOptional(rawValue);
flattenedValues.add(new FetchedValue(listResult, rawValue));
}
Expand Down Expand Up @@ -449,15 +452,32 @@ private BiFunction<List<Object>, Throwable, List<FetchedValue>> handleResult(Exe
}

private List<Object> assertResult(List<MapOrList> parentResults, Object result) {
if (result != null && !(result instanceof List)) {
throw new BatchAssertionFailed("invalid result from DataFetcher: List expected");
result = convertPossibleArray(result);
if (result != null && !(result instanceof Iterable)) {
throw new BatchAssertionFailed(String.format("BatchedDataFetcher provided an invalid result: Iterable expected but got '%s'. Affected fields are set to null.", result.getClass().getName()));
}
@SuppressWarnings("unchecked")
List<Object> values = (List<Object>) result;
if (values == null || values.size() != parentResults.size()) {
throw new BatchAssertionFailed("BatchedDataFetcher provided invalid number of result values. Affected fields are set to null.");
Iterable<Object> iterableResult = (Iterable<Object>) result;
if (iterableResult == null) {
throw new BatchAssertionFailed("BatchedDataFetcher provided a null Iterable of result values. Affected fields are set to null.");
}
return values;
List<Object> resultList = new ArrayList<>();
iterableResult.forEach(resultList::add);

long size = resultList.size();
if (size != parentResults.size()) {
throw new BatchAssertionFailed(String.format("BatchedDataFetcher provided invalid number of result values, expected %d but got %d. Affected fields are set to null.", parentResults.size(), size));
}
return resultList;
}

private Object convertPossibleArray(Object result) {
if (result != null && result.getClass().isArray()) {
return IntStream.range(0, Array.getLength(result))
.mapToObj(i -> Array.get(result, i))
.collect(toList());
}
return result;
}

private BatchedDataFetcher getDataFetcher(GraphQLFieldDefinition fieldDef) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -384,11 +384,20 @@ class BatchedExecutionStrategyTest extends Specification {
given:
String query = "{ string(value: \"673-optional-support\"){emptyOptional, optional} }"

def expected = [string: [emptyOptional:null, optional:"673-optional-support"]]
def expected = [string: [emptyOptional: null, optional: "673-optional-support"]]
println expected

expect:
runTest(query, expected)
}


def "Any Iterable is accepted as GraphQL list value"() {
given:
String query = "{ string(value: \"test\"){ anyIterable } }"
Map<String, Object> expected = ["string": ["anyIterable": ["test", "end"]]]
expect:
runTest(query, expected)
}

}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test from the other PR

Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
package graphql.execution.batched;

import graphql.Scalars;
import graphql.schema.*;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import graphql.schema.GraphQLArgument;
import graphql.schema.GraphQLEnumType;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLList;
import graphql.schema.GraphQLNonNull;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLSchema;
import graphql.schema.GraphQLTypeReference;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
Expand All @@ -12,7 +24,7 @@
public class FunWithStringsSchemaFactory {


public static void increment(Map<CallType, AtomicInteger> callCounts, CallType type) {
private static void increment(Map<CallType, AtomicInteger> callCounts, CallType type) {
if (!callCounts.containsKey(type)) {
callCounts.put(type, new AtomicInteger(0));
}
Expand All @@ -34,7 +46,7 @@ public static FunWithStringsSchemaFactory createBatched(final Map<CallType, Atom
public Object get(DataFetchingEnvironment environment) {
increment(callCounts, CallType.VALUE);
List<String> retVal = new ArrayList<>();
for (String s: (List<String>) environment.getSource()) {
for (String s : (List<String>) environment.getSource()) {
retVal.add("null".equals(s) ? null : s);
}
return retVal;
Expand All @@ -55,25 +67,39 @@ public Object get(DataFetchingEnvironment environment) {
@SuppressWarnings("unchecked")
public Object get(DataFetchingEnvironment environment) {
List<String> retVal = new ArrayList<>();
for (String s: (List<String>) environment.getSource()) {
for (String s : (List<String>) environment.getSource()) {
retVal.add("null".equals(s) ? null : s);
}
retVal.add("badValue");
return retVal;
}
});

factory.setAnyIterable(new DataFetcher() {
@Override
@Batched
@SuppressWarnings("unchecked")
public Object get(DataFetchingEnvironment environment) {
List<Iterable<String>> retVal = new ArrayList<>();
for (String s : (List<String>) environment.getSource()) {
retVal.add(new LinkedHashSet<>(Arrays.asList(s, "end")));
}
return retVal;
}
});

factory.setAppendFetcher(new DataFetcher() {
@Override
@Batched
@SuppressWarnings("unchecked")
public Object get(DataFetchingEnvironment environment) {
increment(callCounts, CallType.APPEND);
List<String> retVal = new ArrayList<>();
for (String s: (List<String>) environment.getSource()) {
for (String s : (List<String>) environment.getSource()) {
retVal.add(s + environment.getArgument("text"));
}
return retVal;
// make it an Iterable thing not just List
return new ArrayDeque<>(retVal);
}
});

Expand All @@ -87,16 +113,10 @@ public Object get(DataFetchingEnvironment environment) {
List<List<List<String>>> retVal = new ArrayList<>();
for (String source : sources) {
List<List<String>> sentence = new ArrayList<>();
for (String word : source.split(" ")) {
List<String> letters = new ArrayList<>();
for (char c : word.toCharArray()) {
letters.add(Character.toString(c));
}
sentence.add(letters);
}
splitSentence(source, sentence);
retVal.add(sentence);
}
return retVal;
return retVal.toArray();
}
});

Expand All @@ -110,14 +130,14 @@ public Object get(DataFetchingEnvironment environment) {
List<String> sources = environment.getSource();
List<List<String>> retVal = new ArrayList<>();
if (regex == null) {
for (String source: sources) {
for (String ignored : sources) {
retVal.add(null);
}
return retVal;
}
for (String source: sources) {
for (String source : sources) {
List<String> retItem = new ArrayList<>();
for (String str: source.split(regex)) {
for (String str : source.split(regex)) {
if (str.isEmpty()) {
retItem.add(null);
} else {
Expand All @@ -138,9 +158,9 @@ public Object get(DataFetchingEnvironment environment) {
increment(callCounts, CallType.SHATTER);
List<String> sources = environment.getSource();
List<List<String>> retVal = new ArrayList<>();
for (String source: sources) {
for (String source : sources) {
List<String> retItem = new ArrayList<>();
for (char c: source.toCharArray()) {
for (char c : source.toCharArray()) {
retItem.add(Character.toString(c));
}
retVal.add(retItem);
Expand All @@ -153,46 +173,58 @@ public Object get(DataFetchingEnvironment environment) {

}

private void setAnyIterable(DataFetcher fetcher) {
this.anyIterableFetcher = fetcher;
}

private static void splitSentence(String source, List<List<String>> sentence) {
for (String word : source.split(" ")) {
List<String> letters = new ArrayList<>();
for (char c : word.toCharArray()) {
letters.add(Character.toString(c));
}
sentence.add(letters);
}
}


private DataFetcher stringObjectValueFetcher = e -> "null".equals(e.getSource()) ? null : e.getSource();

private DataFetcher throwExceptionFetcher = e -> { throw new RuntimeException("TestException"); };
private DataFetcher throwExceptionFetcher = e -> {
throw new RuntimeException("TestException");
};

private DataFetcher returnBadListFetcher = e -> { throw new RuntimeException("This field should only be queried in batch."); };
private DataFetcher returnBadListFetcher = e -> {
throw new RuntimeException("This field should only be queried in batch.");
};

private DataFetcher shatterFetcher = e -> {
String source = e.getSource();
if(source.isEmpty()) {
if (source.isEmpty()) {
return null; // trigger error
}
List<String> retVal = new ArrayList<>();
for (char c: source.toCharArray()) {
for (char c : source.toCharArray()) {
retVal.add(Character.toString(c));
}
return retVal;
};

public DataFetcher wordsAndLettersFetcher = e -> {
private DataFetcher wordsAndLettersFetcher = e -> {
String source = e.getSource();
List<List<String>> retVal = new ArrayList<>();
for (String word: source.split(" ")) {
List<String> retItem = new ArrayList<>();
for (char c: word.toCharArray()) {
retItem.add(Character.toString(c));
}
retVal.add(retItem);
}
splitSentence(source, retVal);
return retVal;
};

public DataFetcher splitFetcher = e -> {
private DataFetcher splitFetcher = e -> {
String regex = e.getArgument("regex");
if (regex == null ) {
if (regex == null) {
return null;
}
String source = e.getSource();
List<String> retVal = new ArrayList<>();
for (String str: source.split(regex)) {
for (String str : source.split(regex)) {
if (str.isEmpty()) {
retVal.add(null);
} else {
Expand All @@ -202,37 +234,42 @@ public Object get(DataFetchingEnvironment environment) {
return retVal;
};

public DataFetcher appendFetcher = e -> ((String)e.getSource()) + e.getArgument("text");
private DataFetcher appendFetcher = e -> ((String) e.getSource()) + e.getArgument("text");

public DataFetcher emptyOptionalFetcher = e -> Optional.empty();
private DataFetcher emptyOptionalFetcher = e -> Optional.empty();

public DataFetcher optionalFetcher = e -> Optional.of("673-optional-support");
private DataFetcher optionalFetcher = e -> Optional.of("673-optional-support");

public void setWordsAndLettersFetcher(DataFetcher fetcher) {
private DataFetcher anyIterableFetcher = e -> {
String source = e.getSource();
return new LinkedHashSet<>(Arrays.asList(source, "end"));
};

private void setWordsAndLettersFetcher(DataFetcher fetcher) {
this.wordsAndLettersFetcher = fetcher;
}

public void setShatterFetcher(DataFetcher fetcher) {
private void setShatterFetcher(DataFetcher fetcher) {
this.shatterFetcher = fetcher;
}

public void setSplitFetcher(DataFetcher splitFetcher) {
private void setSplitFetcher(DataFetcher splitFetcher) {
this.splitFetcher = splitFetcher;
}

public void setAppendFetcher(DataFetcher appendFetcher) {
private void setAppendFetcher(DataFetcher appendFetcher) {
this.appendFetcher = appendFetcher;
}

public void setStringObjectValueFetcher(DataFetcher fetcher) {
private void setStringObjectValueFetcher(DataFetcher fetcher) {
this.stringObjectValueFetcher = fetcher;
}

public void setThrowExceptionFetcher(DataFetcher fetcher) {
private void setThrowExceptionFetcher(DataFetcher fetcher) {
this.throwExceptionFetcher = fetcher;
}

public void setReturnBadList(DataFetcher fetcher) {
private void setReturnBadList(DataFetcher fetcher) {
this.returnBadListFetcher = fetcher;
}

Expand Down Expand Up @@ -260,14 +297,18 @@ GraphQLSchema createSchema() {
.name("returnBadList")
.type(Scalars.GraphQLString)
.dataFetcher(returnBadListFetcher))
.field(GraphQLFieldDefinition.newFieldDefinition()
.name("anyIterable")
.type(new GraphQLList(Scalars.GraphQLString))
.dataFetcher(anyIterableFetcher))
.field(GraphQLFieldDefinition.newFieldDefinition()
.name("shatter")
.type(new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(new GraphQLTypeReference("StringObject")))))
.dataFetcher(shatterFetcher))

.field(GraphQLFieldDefinition.newFieldDefinition()
.name("wordsAndLetters")
.type(new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(new GraphQLList(new GraphQLNonNull( new GraphQLNonNull(new GraphQLTypeReference("StringObject"))))))))
.type(new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(new GraphQLNonNull(new GraphQLTypeReference("StringObject"))))))))
.dataFetcher(wordsAndLettersFetcher))

.field(GraphQLFieldDefinition.newFieldDefinition()
Expand Down