Skip to content

Commit 2daa0a9

Browse files
committed
query with dynamic arguments (variables)
1 parent a0b488c commit 2daa0a9

3 files changed

Lines changed: 39 additions & 3 deletions

File tree

src/main/java/graphql/GraphQL.java

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,32 @@
66
import graphql.parser.Parser;
77
import graphql.schema.GraphQLSchema;
88

9+
import java.util.Collections;
10+
import java.util.LinkedHashMap;
11+
import java.util.Map;
12+
913
public class GraphQL {
1014

1115

12-
private GraphQLSchema graphQLSchema;
13-
private String requestString;
16+
private final GraphQLSchema graphQLSchema;
17+
private final String requestString;
18+
private final Map<String, Object> arguments = new LinkedHashMap<>();
1419

1520
public GraphQL(GraphQLSchema graphQLSchema, String requestString) {
21+
this(graphQLSchema, requestString, Collections.<String, Object>emptyMap());
22+
}
23+
24+
public GraphQL(GraphQLSchema graphQLSchema, String requestString, Map<String, Object> arguments) {
1625
this.graphQLSchema = graphQLSchema;
1726
this.requestString = requestString;
27+
this.arguments.putAll(arguments);
1828
}
1929

2030
public Object execute() {
2131
Parser parser = new Parser();
2232
Document document = parser.parseDocument(requestString);
2333
Execution execution = new Execution();
24-
return execution.execute(graphQLSchema, null, document, null, null).getResut();
34+
return execution.execute(graphQLSchema, null, document, null, arguments).getResut();
2535
}
2636

2737

src/main/java/graphql/schema/SchemaUtil.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ private static void collectTypes(GraphQLType root, Map<String, GraphQLType> resu
2424
collectTypesForUnions((GraphQLUnionType) root, result);
2525
} else if (root instanceof GraphQLInputObjectType) {
2626
result.put(((GraphQLInputObjectType) root).getName(),root);
27+
} else if (root instanceof GraphQLTypeReference) {
28+
2729
} else {
2830
throw new RuntimeException("Unknown type " + root);
2931
}

src/test/groovy/graphql/StarWarsQueryTest.groovy

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,4 +172,28 @@ class StarWarsQueryTest extends Specification {
172172
result == expected
173173
}
174174

175+
def 'Allows us to create a generic query, then use it to fetch Luke Skywalker using his ID'() {
176+
given:
177+
def query = """
178+
query FetchSomeIDQuery(\$someId: String!) {
179+
human(id: \$someId) {
180+
name
181+
}
182+
}
183+
"""
184+
def params = [
185+
someId: '1000'
186+
]
187+
def expected = [
188+
human: [
189+
name: 'Luke Skywalker'
190+
]
191+
]
192+
when:
193+
def result = new GraphQL(StarWarsSchema.starWarsSchema, query, params).execute()
194+
195+
then:
196+
result == expected
197+
}
198+
175199
}

0 commit comments

Comments
 (0)