use of graphql.schema.DataFetcher in project graphql-java by graphql-java.
the class FunWithStringsSchemaFactory method createBatched.
public static FunWithStringsSchemaFactory createBatched(final Map<CallType, AtomicInteger> callCounts) {
FunWithStringsSchemaFactory factory = new FunWithStringsSchemaFactory();
factory.setStringObjectValueFetcher(new DataFetcher() {
@Override
@Batched
@SuppressWarnings("unchecked")
public Object get(DataFetchingEnvironment environment) {
increment(callCounts, CallType.VALUE);
List<String> retVal = new ArrayList<>();
for (String s : (List<String>) environment.getSource()) {
retVal.add("null".equals(s) ? null : s);
}
return retVal;
}
});
factory.setThrowExceptionFetcher(new DataFetcher() {
@Override
@Batched
public Object get(DataFetchingEnvironment environment) {
throw new RuntimeException("TestException");
}
});
factory.setReturnBadList(new DataFetcher() {
@Override
@Batched
@SuppressWarnings("unchecked")
public Object get(DataFetchingEnvironment environment) {
List<String> retVal = new ArrayList<>();
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()) {
retVal.add(s + environment.getArgument("text"));
}
// make it an Iterable thing not just List
return new ArrayDeque<>(retVal);
}
});
factory.setWordsAndLettersFetcher(new DataFetcher() {
@Batched
@Override
@SuppressWarnings("unchecked")
public Object get(DataFetchingEnvironment environment) {
increment(callCounts, CallType.WORDS_AND_LETTERS);
List<String> sources = environment.getSource();
List<List<List<String>>> retVal = new ArrayList<>();
for (String source : sources) {
List<List<String>> sentence = new ArrayList<>();
splitSentence(source, sentence);
retVal.add(sentence);
}
return retVal.toArray();
}
});
factory.setSplitFetcher(new DataFetcher() {
@Batched
@Override
@SuppressWarnings("unchecked")
public Object get(DataFetchingEnvironment environment) {
increment(callCounts, CallType.SPLIT);
String regex = environment.getArgument("regex");
List<String> sources = environment.getSource();
List<List<String>> retVal = new ArrayList<>();
if (regex == null) {
for (String ignored : sources) {
retVal.add(null);
}
return retVal;
}
for (String source : sources) {
List<String> retItem = new ArrayList<>();
for (String str : source.split(regex)) {
if (str.isEmpty()) {
retItem.add(null);
} else {
retItem.add(str);
}
}
retVal.add(retItem);
}
return retVal;
}
});
factory.setShatterFetcher(new DataFetcher() {
@Batched
@Override
@SuppressWarnings("unchecked")
public Object get(DataFetchingEnvironment environment) {
increment(callCounts, CallType.SHATTER);
List<String> sources = environment.getSource();
List<List<String>> retVal = new ArrayList<>();
for (String source : sources) {
List<String> retItem = new ArrayList<>();
for (char c : source.toCharArray()) {
retItem.add(Character.toString(c));
}
retVal.add(retItem);
}
return retVal;
}
});
return factory;
}
use of graphql.schema.DataFetcher in project graphql-java by graphql-java.
the class FunWithStringsSchemaFactory method createSchema.
GraphQLSchema createSchema() {
GraphQLObjectType stringObjectType = newObject().name("StringObject").field(newFieldDefinition().name("value").type(GraphQLString).dataFetcher(stringObjectValueFetcher)).field(newFieldDefinition().name("nonNullValue").type(new GraphQLNonNull(GraphQLString)).dataFetcher(stringObjectValueFetcher)).field(newFieldDefinition().name("veryNonNullValue").type(new GraphQLNonNull(new GraphQLNonNull(GraphQLString))).dataFetcher(stringObjectValueFetcher)).field(newFieldDefinition().name("throwException").type(GraphQLString).dataFetcher(throwExceptionFetcher)).field(newFieldDefinition().name("returnBadList").type(GraphQLString).dataFetcher(returnBadListFetcher)).field(newFieldDefinition().name("anyIterable").type(new GraphQLList(GraphQLString)).dataFetcher(anyIterableFetcher)).field(newFieldDefinition().name("shatter").type(new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(new GraphQLTypeReference("StringObject"))))).dataFetcher(shatterFetcher)).field(newFieldDefinition().name("wordsAndLetters").type(new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(new GraphQLNonNull(new GraphQLTypeReference("StringObject")))))))).dataFetcher(wordsAndLettersFetcher)).field(newFieldDefinition().name("split").description("String#split(regex) but replace empty strings with nulls to help us test null behavior in lists").type(new GraphQLList(new GraphQLTypeReference("StringObject"))).argument(GraphQLArgument.newArgument().name("regex").type(GraphQLString)).dataFetcher(splitFetcher)).field(newFieldDefinition().name("splitNotNull").description("String#split(regex) but replace empty strings with nulls to help us test null behavior in lists").type(new GraphQLList(new GraphQLNonNull(new GraphQLTypeReference("StringObject")))).argument(GraphQLArgument.newArgument().name("regex").type(GraphQLString)).dataFetcher(splitFetcher)).field(newFieldDefinition().name("append").type(new GraphQLTypeReference("StringObject")).argument(GraphQLArgument.newArgument().name("text").type(GraphQLString)).dataFetcher(appendFetcher)).field(newFieldDefinition().name("emptyOptional").type(GraphQLString).argument(GraphQLArgument.newArgument().name("text").type(GraphQLString)).dataFetcher(emptyOptionalFetcher)).field(newFieldDefinition().name("optional").type(GraphQLString).argument(GraphQLArgument.newArgument().name("text").type(GraphQLString)).dataFetcher(optionalFetcher)).field(newFieldDefinition().name("completableFuture").type(GraphQLString).argument(GraphQLArgument.newArgument().name("text").type(GraphQLString)).dataFetcher(completableFutureFetcher)).build();
GraphQLEnumType enumDayType = newEnum().name("Day").value("MONDAY").value("TUESDAY").description("Day of the week").build();
GraphQLObjectType simpleObjectType = newObject().name("SimpleObject").field(newFieldDefinition().name("value").type(GraphQLString)).build();
GraphQLInterfaceType interfaceType = newInterface().name("InterfaceType").field(newFieldDefinition().name("value").type(GraphQLString)).typeResolver(env -> {
// always this for testing
return simpleObjectType;
}).build();
GraphQLObjectType queryType = newObject().name("StringQuery").field(newFieldDefinition().name("string").type(stringObjectType).argument(GraphQLArgument.newArgument().name("value").type(GraphQLString)).dataFetcher(env -> env.getArgument("value"))).field(newFieldDefinition().name("interface").type(interfaceType).argument(GraphQLArgument.newArgument().name("value").type(GraphQLString)).dataFetcher(env -> CompletableFuture.completedFuture(new SimpleObject()))).field(newFieldDefinition().name("nullEnum").type(enumDayType).dataFetcher(env -> null)).build();
return GraphQLSchema.newSchema().query(queryType).build();
}
use of graphql.schema.DataFetcher in project ontrack by nemerosa.
the class GQLRootQueryBranches method branchFetcher.
private DataFetcher branchFetcher() {
return environment -> {
Integer id = environment.getArgument("id");
String projectName = environment.getArgument("project");
String name = environment.getArgument("name");
Object propertyFilterArg = environment.getArgument(GQLInputPropertyFilter.ARGUMENT_NAME);
// Per ID
if (id != null) {
checkArgList(environment, "id");
return Collections.singletonList(structureService.getBranch(ID.of(id)));
} else // Per project name, name or property filter
if (isNotBlank(projectName) || isNotBlank(name) || propertyFilterArg != null) {
// Project filter
Predicate<Project> projectFilter = p -> true;
if (isNotBlank(projectName)) {
projectFilter = projectFilter.and(project -> StringUtils.equals(projectName, project.getName()));
}
// Branch filter
Predicate<Branch> branchFilter = b -> true;
if (isNotBlank(name)) {
Pattern pattern = Pattern.compile(name);
branchFilter = branchFilter.and(b -> pattern.matcher(b.getName()).matches());
}
// Property filter?
if (propertyFilterArg != null) {
PropertyFilter filterObject = propertyFilter.convert(propertyFilterArg);
if (filterObject != null && StringUtils.isNotBlank(filterObject.getType())) {
branchFilter = branchFilter.and(propertyFilter.getFilter(filterObject));
}
}
// Gets the list of authorised projects
return structureService.getProjectList().stream().filter(projectFilter).flatMap(project -> structureService.getBranchesForProject(project.getId()).stream()).filter(branchFilter).collect(Collectors.toList());
} else // No result to return
{
return Collections.emptyList();
}
};
}
use of graphql.schema.DataFetcher in project graphql-java by graphql-java.
the class ExecutionStrategy method fetchField.
/**
* Called to fetch a value for a field from the {@link DataFetcher} associated with the field
* {@link GraphQLFieldDefinition}.
* <p>
* Graphql fragments mean that for any give logical field can have one or more {@link Field} values associated with it
* in the query, hence the fieldList. However the first entry is representative of the field for most purposes.
*
* @param executionContext contains the top level execution parameters
* @param parameters contains the parameters holding the fields to be executed and source object
*
* @return a fetched object
*
* @throws NonNullableFieldWasNullException if a non null field resolves to a null value
*/
protected CompletableFuture<Object> fetchField(ExecutionContext executionContext, ExecutionStrategyParameters parameters) {
Field field = parameters.getField().get(0);
GraphQLObjectType parentType = parameters.getTypeInfo().castType(GraphQLObjectType.class);
GraphQLFieldDefinition fieldDef = getFieldDef(executionContext.getGraphQLSchema(), parentType, field);
GraphqlFieldVisibility fieldVisibility = executionContext.getGraphQLSchema().getFieldVisibility();
Map<String, Object> argumentValues = valuesResolver.getArgumentValues(fieldVisibility, fieldDef.getArguments(), field.getArguments(), executionContext.getVariables());
GraphQLOutputType fieldType = fieldDef.getType();
DataFetchingFieldSelectionSet fieldCollector = DataFetchingFieldSelectionSetImpl.newCollector(executionContext, fieldType, parameters.getField());
ExecutionTypeInfo fieldTypeInfo = fieldTypeInfo(parameters, fieldDef);
DataFetchingEnvironment environment = newDataFetchingEnvironment(executionContext).source(parameters.getSource()).arguments(argumentValues).fieldDefinition(fieldDef).fields(parameters.getField()).fieldType(fieldType).fieldTypeInfo(fieldTypeInfo).parentType(parentType).selectionSet(fieldCollector).build();
Instrumentation instrumentation = executionContext.getInstrumentation();
InstrumentationFieldFetchParameters instrumentationFieldFetchParams = new InstrumentationFieldFetchParameters(executionContext, fieldDef, environment);
InstrumentationContext<Object> fetchCtx = instrumentation.beginFieldFetch(instrumentationFieldFetchParams);
CompletableFuture<Object> fetchedValue;
DataFetcher dataFetcher = fieldDef.getDataFetcher();
dataFetcher = instrumentation.instrumentDataFetcher(dataFetcher, instrumentationFieldFetchParams);
ExecutionId executionId = executionContext.getExecutionId();
try {
log.debug("'{}' fetching field '{}' using data fetcher '{}'...", executionId, fieldTypeInfo.getPath(), dataFetcher.getClass().getName());
Object fetchedValueRaw = dataFetcher.get(environment);
log.debug("'{}' field '{}' fetch returned '{}'", executionId, fieldTypeInfo.getPath(), fetchedValueRaw == null ? "null" : fetchedValueRaw.getClass().getName());
fetchedValue = Async.toCompletableFuture(fetchedValueRaw);
} catch (Exception e) {
log.debug(String.format("'%s', field '%s' fetch threw exception", executionId, fieldTypeInfo.getPath()), e);
fetchedValue = new CompletableFuture<>();
fetchedValue.completeExceptionally(e);
}
fetchCtx.onDispatched(fetchedValue);
return fetchedValue.handle((result, exception) -> {
fetchCtx.onCompleted(result, exception);
if (exception != null) {
handleFetchingException(executionContext, parameters, field, fieldDef, argumentValues, environment, exception);
return null;
} else {
return result;
}
}).thenApply(result -> unboxPossibleDataFetcherResult(executionContext, parameters, result)).thenApply(this::unboxPossibleOptional);
}
use of graphql.schema.DataFetcher in project graphql-java by graphql-java.
the class HttpMain method buildStarWarsSchema.
private GraphQLSchema buildStarWarsSchema() {
//
if (starWarsSchema == null) {
//
//
// the fetcher of friends uses java-dataloader to make the circular friends fetching
// more efficient by batching and caching the calls to load Character friends
//
DataFetcher friendsFetcher = environment -> {
DataLoaderRegistry dataloaderRegistry = asMapGet(environment.getContext(), "dataloaderRegistry");
DataLoader friendsDataLoader = dataloaderRegistry.getDataLoader("friends");
List<String> friendIds = asMapGet(environment.getSource(), "friends");
return friendsDataLoader.loadMany(friendIds);
};
//
// reads a file that provides the schema types
//
Reader streamReader = loadSchemaFile("starWarsSchemaAnnotated.graphqls");
TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(streamReader);
//
// the runtime wiring is used to provide the code that backs the
// logical schema
//
TypeResolver characterTypeResolver = env -> {
Map<String, Object> obj = (Map<String, Object>) env.getObject();
String id = (String) obj.get("id");
GraphQLSchema schema = env.getSchema();
if (StarWarsData.isHuman(id)) {
return (GraphQLObjectType) schema.getType("Human");
} else {
return (GraphQLObjectType) schema.getType("Droid");
}
};
RuntimeWiring wiring = RuntimeWiring.newRuntimeWiring().type(newTypeWiring("Query").dataFetcher("hero", StarWarsData.getHeroDataFetcher()).dataFetcher("human", StarWarsData.getHumanDataFetcher()).dataFetcher("droid", StarWarsData.getDroidDataFetcher())).type(newTypeWiring("Human").dataFetcher("friends", friendsFetcher)).type(newTypeWiring("Droid").dataFetcher("friends", friendsFetcher)).type(newTypeWiring("Character").typeResolver(characterTypeResolver)).type(newTypeWiring("Episode").enumValues(StarWarsData.getEpisodeResolver())).build();
// finally combine the logical schema with the physical runtime
starWarsSchema = new SchemaGenerator().makeExecutableSchema(typeRegistry, wiring);
}
return starWarsSchema;
}
Aggregations