use of graphql.schema.DataFetchingEnvironment in project engine by craftercms.
the class ContentTypeBasedDataFetcher method addFieldFilterFromMapEntry.
protected void addFieldFilterFromMapEntry(String path, Map.Entry<String, Object> filter, BoolQueryBuilder query, DataFetchingEnvironment env) {
if (filter.getValue() instanceof List) {
List<Map<String, Object>> actualFilters = (List<Map<String, Object>>) filter.getValue();
switch(filter.getKey()) {
case ARG_NAME_NOT:
BoolQueryBuilder notQuery = boolQuery();
actualFilters.forEach(notFilter -> notFilter.entrySet().forEach(notField -> addFieldFilterFromMapEntry(path, notField, notQuery, env)));
notQuery.filter().forEach(query::mustNot);
break;
case ARG_NAME_AND:
actualFilters.forEach(andFilter -> andFilter.entrySet().forEach(andField -> addFieldFilterFromMapEntry(path, andField, query, env)));
break;
case ARG_NAME_OR:
BoolQueryBuilder tempQuery = boolQuery();
BoolQueryBuilder orQuery = boolQuery();
actualFilters.forEach(orFilter -> orFilter.entrySet().forEach(orField -> addFieldFilterFromMapEntry(path, orField, tempQuery, env)));
tempQuery.filter().forEach(orQuery::should);
query.filter(boolQuery().must(orQuery));
break;
default:
}
} else {
query.filter(getFilterQueryFromMapEntry(path, filter));
}
}
use of graphql.schema.DataFetchingEnvironment in project engine by craftercms.
the class ContentTypeBasedDataFetcher method doGet.
/**
* {@inheritDoc}
*/
@Override
public Object doGet(final DataFetchingEnvironment env) {
Field field = env.getMergedField().getSingleField();
String fieldName = field.getName();
// Get arguments for pagination & sorting
int offset = Optional.ofNullable(env.<Integer>getArgument(ARG_NAME_OFFSET)).orElse(0);
int limit = Optional.ofNullable(env.<Integer>getArgument(ARG_NAME_LIMIT)).orElse(defaultLimit);
String sortBy = Optional.ofNullable(env.<String>getArgument(ARG_NAME_SORT_BY)).orElse(defaultSortField);
String sortOrder = Optional.ofNullable(env.<String>getArgument(ARG_NAME_SORT_ORDER)).orElse(defaultSortOrder);
List<String> queryFieldIncludes = new LinkedList<>();
// Add content-type to includes, we might need it for a GraphQL TypeResolver
queryFieldIncludes.add(QUERY_FIELD_NAME_CONTENT_TYPE);
List<Map<String, Object>> items = new LinkedList<>();
Map<String, Object> result = new HashMap<>(2);
result.put(FIELD_NAME_ITEMS, items);
// Setup the ES query
SearchSourceBuilder source = new SearchSourceBuilder();
BoolQueryBuilder query = boolQuery();
source.query(query).from(offset).size(limit).sort(sortBy, SortOrder.fromString(sortOrder));
StopWatch watch = new StopWatch(field.getName() + " - " + field.getAlias());
watch.start("build filters");
// Filter by the content-type
switch(fieldName) {
case FIELD_NAME_CONTENT_ITEMS:
query.filter(existsQuery(QUERY_FIELD_NAME_CONTENT_TYPE));
break;
case FIELD_NAME_PAGES:
query.filter(regexpQuery(QUERY_FIELD_NAME_CONTENT_TYPE, CONTENT_TYPE_REGEX_PAGE));
break;
case FIELD_NAME_COMPONENTS:
query.filter(regexpQuery(QUERY_FIELD_NAME_CONTENT_TYPE, CONTENT_TYPE_REGEX_COMPONENT));
break;
default:
// Get the content-type name from the field name
query.filter(termQuery(QUERY_FIELD_NAME_CONTENT_TYPE, getOriginalName(fieldName)));
break;
}
// Check the selected fields to build the ES query
Optional<Field> itemsField = field.getSelectionSet().getSelections().stream().map(f -> (Field) f).filter(f -> f.getName().equals(FIELD_NAME_ITEMS)).findFirst();
if (itemsField.isPresent()) {
List<Selection> selections = itemsField.get().getSelectionSet().getSelections();
selections.forEach(selection -> processSelection(StringUtils.EMPTY, selection, query, queryFieldIncludes, env));
}
// Only fetch the selected fields for better performance
source.fetchSource(queryFieldIncludes.toArray(new String[0]), new String[0]);
watch.stop();
logger.debug("Executing query: {}", source);
watch.start("searching items");
SearchResponse response = elasticsearch.search(new SearchRequest().source(source));
watch.stop();
watch.start("processing items");
result.put(FIELD_NAME_TOTAL, response.getHits().totalHits);
if (response.getHits().totalHits > 0) {
for (SearchHit hit : response.getHits().getHits()) {
items.add(fixItems(hit.getSourceAsMap()));
}
}
watch.stop();
if (logger.isTraceEnabled()) {
logger.trace(watch.prettyPrint());
}
return result;
}
use of graphql.schema.DataFetchingEnvironment in project admin-console-beta by connexta.
the class ExecutionStrategyImpl method resolveField.
@Override
protected ExecutionResult resolveField(ExecutionContext executionContext, GraphQLObjectType parentType, Object source, List<Field> fields) {
GraphQLFieldDefinition fieldDef = getFieldDef(executionContext.getGraphQLSchema(), parentType, fields.get(0));
Map<String, Object> argumentValues = valuesResolver.getArgumentValues(fieldDef.getArguments(), fields.get(0).getArguments(), executionContext.getVariables());
DataFetchingEnvironment environment = new DataFetchingEnvironment(source, argumentValues, executionContext.getRoot(), fields, fieldDef.getType(), parentType, executionContext.getGraphQLSchema());
Object resolvedValue = null;
try {
resolvedValue = fieldDef.getDataFetcher().get(environment);
if (resolvedValue instanceof FunctionReport) {
FunctionReport<DataType> report = ((FunctionReport) resolvedValue);
resolvedValue = report.isResultPresent() ? report.result().getValue() : null;
List<Message> msgs = report.messages();
msgs.stream().map(GraphQLErrorMessageWrapper::new).forEach(executionContext::addError);
}
} catch (Exception e) {
LOGGER.info("Exception while fetching data", e);
executionContext.addError(new ExceptionWhileDataFetching(e));
}
return completeValue(executionContext, fieldDef.getType(), fields, resolvedValue);
}
use of graphql.schema.DataFetchingEnvironment 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.DataFetchingEnvironment in project graphql-java by graphql-java.
the class BatchedExecutionStrategy method fetchData.
private CompletableFuture<FetchedValues> fetchData(ExecutionContext executionContext, ExecutionStrategyParameters parameters, String fieldName, ExecutionNode node, GraphQLFieldDefinition fieldDef) {
GraphQLObjectType parentType = node.getType();
List<Field> fields = node.getFields().get(fieldName);
List<MapOrList> parentResults = node.getParentResults();
GraphqlFieldVisibility fieldVisibility = executionContext.getGraphQLSchema().getFieldVisibility();
Map<String, Object> argumentValues = valuesResolver.getArgumentValues(fieldVisibility, fieldDef.getArguments(), fields.get(0).getArguments(), executionContext.getVariables());
GraphQLOutputType fieldType = fieldDef.getType();
DataFetchingFieldSelectionSet fieldCollector = DataFetchingFieldSelectionSetImpl.newCollector(executionContext, fieldType, fields);
DataFetchingEnvironment environment = newDataFetchingEnvironment(executionContext).source(node.getSources()).arguments(argumentValues).fieldDefinition(fieldDef).fields(fields).fieldType(fieldDef.getType()).fieldTypeInfo(parameters.getTypeInfo()).parentType(parentType).selectionSet(fieldCollector).build();
Instrumentation instrumentation = executionContext.getInstrumentation();
InstrumentationFieldFetchParameters instrumentationFieldFetchParameters = new InstrumentationFieldFetchParameters(executionContext, fieldDef, environment);
InstrumentationContext<Object> fetchCtx = instrumentation.beginFieldFetch(instrumentationFieldFetchParameters);
CompletableFuture<Object> fetchedValue;
try {
DataFetcher<?> dataFetcher = instrumentation.instrumentDataFetcher(getDataFetcher(fieldDef), instrumentationFieldFetchParameters);
Object fetchedValueRaw = dataFetcher.get(environment);
fetchedValue = Async.toCompletableFuture(fetchedValueRaw);
} catch (Exception e) {
fetchedValue = new CompletableFuture<>();
fetchedValue.completeExceptionally(e);
}
return fetchedValue.thenApply((result) -> assertResult(parentResults, result)).whenComplete(fetchCtx::onCompleted).handle(handleResult(executionContext, parameters, parentResults, fields, fieldDef, argumentValues, environment));
}
Aggregations