Search in sources :

Example 6 with DataFetchingEnvironment

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));
    }
}
Also used : ObjectValue(graphql.language.ObjectValue) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) FloatValue(graphql.language.FloatValue) Value(graphql.language.Value) LoggerFactory(org.slf4j.LoggerFactory) FragmentSpread(graphql.language.FragmentSpread) HashMap(java.util.HashMap) SearchRequest(org.elasticsearch.action.search.SearchRequest) QueryBuilders(org.elasticsearch.index.query.QueryBuilders) StringUtils(org.apache.commons.lang3.StringUtils) ElasticsearchWrapper(org.craftercms.search.elasticsearch.ElasticsearchWrapper) LinkedHashMap(java.util.LinkedHashMap) Selection(graphql.language.Selection) VariableReference(graphql.language.VariableReference) Map(java.util.Map) SearchResponse(org.elasticsearch.action.search.SearchResponse) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) DataFetcher(graphql.schema.DataFetcher) LinkedList(java.util.LinkedList) SearchHit(org.elasticsearch.search.SearchHit) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) Logger(org.slf4j.Logger) MapUtils(org.apache.commons.collections.MapUtils) ObjectField(graphql.language.ObjectField) StopWatch(org.springframework.util.StopWatch) Field(graphql.language.Field) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) Argument(graphql.language.Argument) List(java.util.List) StringValue(graphql.language.StringValue) ArrayValue(graphql.language.ArrayValue) IntValue(graphql.language.IntValue) SortOrder(org.elasticsearch.search.sort.SortOrder) Optional(java.util.Optional) FragmentDefinition(graphql.language.FragmentDefinition) Required(org.springframework.beans.factory.annotation.Required) InlineFragment(graphql.language.InlineFragment) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) Collections(java.util.Collections) SchemaUtils(org.craftercms.engine.graphql.SchemaUtils) BooleanValue(graphql.language.BooleanValue) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) LinkedList(java.util.LinkedList) List(java.util.List) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 7 with DataFetchingEnvironment

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;
}
Also used : ObjectValue(graphql.language.ObjectValue) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) FloatValue(graphql.language.FloatValue) Value(graphql.language.Value) LoggerFactory(org.slf4j.LoggerFactory) FragmentSpread(graphql.language.FragmentSpread) HashMap(java.util.HashMap) SearchRequest(org.elasticsearch.action.search.SearchRequest) QueryBuilders(org.elasticsearch.index.query.QueryBuilders) StringUtils(org.apache.commons.lang3.StringUtils) ElasticsearchWrapper(org.craftercms.search.elasticsearch.ElasticsearchWrapper) LinkedHashMap(java.util.LinkedHashMap) Selection(graphql.language.Selection) VariableReference(graphql.language.VariableReference) Map(java.util.Map) SearchResponse(org.elasticsearch.action.search.SearchResponse) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) DataFetcher(graphql.schema.DataFetcher) LinkedList(java.util.LinkedList) SearchHit(org.elasticsearch.search.SearchHit) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) Logger(org.slf4j.Logger) MapUtils(org.apache.commons.collections.MapUtils) ObjectField(graphql.language.ObjectField) StopWatch(org.springframework.util.StopWatch) Field(graphql.language.Field) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) Argument(graphql.language.Argument) List(java.util.List) StringValue(graphql.language.StringValue) ArrayValue(graphql.language.ArrayValue) IntValue(graphql.language.IntValue) SortOrder(org.elasticsearch.search.sort.SortOrder) Optional(java.util.Optional) FragmentDefinition(graphql.language.FragmentDefinition) Required(org.springframework.beans.factory.annotation.Required) InlineFragment(graphql.language.InlineFragment) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) Collections(java.util.Collections) SchemaUtils(org.craftercms.engine.graphql.SchemaUtils) BooleanValue(graphql.language.BooleanValue) SearchRequest(org.elasticsearch.action.search.SearchRequest) SearchHit(org.elasticsearch.search.SearchHit) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Selection(graphql.language.Selection) LinkedList(java.util.LinkedList) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) StopWatch(org.springframework.util.StopWatch) SearchResponse(org.elasticsearch.action.search.SearchResponse) ObjectField(graphql.language.ObjectField) Field(graphql.language.Field) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 8 with DataFetchingEnvironment

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);
}
Also used : Message(org.codice.ddf.admin.api.report.Message) GraphQLFieldDefinition(graphql.schema.GraphQLFieldDefinition) FunctionReport(org.codice.ddf.admin.api.report.FunctionReport) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) DataType(org.codice.ddf.admin.api.DataType) ExceptionWhileDataFetching(graphql.ExceptionWhileDataFetching)

Example 9 with DataFetchingEnvironment

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);
}
Also used : IntStream(java.util.stream.IntStream) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) DataFetchingEnvironmentBuilder.newDataFetchingEnvironment(graphql.schema.DataFetchingEnvironmentBuilder.newDataFetchingEnvironment) Array(java.lang.reflect.Array) GraphQLScalarType(graphql.schema.GraphQLScalarType) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) GraphQLFieldDefinition(graphql.schema.GraphQLFieldDefinition) LoggerFactory(org.slf4j.LoggerFactory) OptionalDouble(java.util.OptionalDouble) GraphQLInterfaceType(graphql.schema.GraphQLInterfaceType) GraphQLUnionType(graphql.schema.GraphQLUnionType) CompletableFuture(java.util.concurrent.CompletableFuture) GraphQLType(graphql.schema.GraphQLType) OptionalInt(java.util.OptionalInt) ArrayList(java.util.ArrayList) ExecutionResult(graphql.ExecutionResult) Introspection(graphql.introspection.Introspection) OptionalLong(java.util.OptionalLong) InstrumentationFieldFetchParameters(graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters) Map(java.util.Map) InstrumentationFieldCompleteParameters(graphql.execution.instrumentation.parameters.InstrumentationFieldCompleteParameters) DataFetcher(graphql.schema.DataFetcher) GraphQLSchema(graphql.schema.GraphQLSchema) ExecutionTypeInfo.newTypeInfo(graphql.execution.ExecutionTypeInfo.newTypeInfo) ExecutionResultImpl(graphql.ExecutionResultImpl) TypeMismatchError(graphql.TypeMismatchError) SerializationError(graphql.SerializationError) TypeResolutionEnvironment(graphql.TypeResolutionEnvironment) GraphQLObjectType(graphql.schema.GraphQLObjectType) CoercingSerializeException(graphql.schema.CoercingSerializeException) Logger(org.slf4j.Logger) PublicSpi(graphql.PublicSpi) GraphqlFieldVisibility(graphql.schema.visibility.GraphqlFieldVisibility) GraphQLOutputType(graphql.schema.GraphQLOutputType) CompletionException(java.util.concurrent.CompletionException) Field(graphql.language.Field) DataFetchingFieldSelectionSetImpl(graphql.schema.DataFetchingFieldSelectionSetImpl) InstrumentationContext(graphql.execution.instrumentation.InstrumentationContext) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) GraphQLList(graphql.schema.GraphQLList) Instrumentation(graphql.execution.instrumentation.Instrumentation) DataFetchingFieldSelectionSet(graphql.schema.DataFetchingFieldSelectionSet) Optional(java.util.Optional) InstrumentationFieldParameters(graphql.execution.instrumentation.parameters.InstrumentationFieldParameters) GraphQLEnumType(graphql.schema.GraphQLEnumType) FieldCollectorParameters.newParameters(graphql.execution.FieldCollectorParameters.newParameters) DataFetchingFieldSelectionSet(graphql.schema.DataFetchingFieldSelectionSet) GraphQLFieldDefinition(graphql.schema.GraphQLFieldDefinition) Instrumentation(graphql.execution.instrumentation.Instrumentation) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) DataFetchingEnvironmentBuilder.newDataFetchingEnvironment(graphql.schema.DataFetchingEnvironmentBuilder.newDataFetchingEnvironment) CoercingSerializeException(graphql.schema.CoercingSerializeException) CompletionException(java.util.concurrent.CompletionException) Field(graphql.language.Field) GraphqlFieldVisibility(graphql.schema.visibility.GraphqlFieldVisibility) GraphQLOutputType(graphql.schema.GraphQLOutputType) CompletableFuture(java.util.concurrent.CompletableFuture) GraphQLObjectType(graphql.schema.GraphQLObjectType) InstrumentationFieldFetchParameters(graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters) DataFetcher(graphql.schema.DataFetcher)

Example 10 with DataFetchingEnvironment

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));
}
Also used : DataFetchingFieldSelectionSet(graphql.schema.DataFetchingFieldSelectionSet) Instrumentation(graphql.execution.instrumentation.Instrumentation) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) DataFetchingEnvironmentBuilder.newDataFetchingEnvironment(graphql.schema.DataFetchingEnvironmentBuilder.newDataFetchingEnvironment) CompletionException(java.util.concurrent.CompletionException) Field(graphql.language.Field) GraphqlFieldVisibility(graphql.schema.visibility.GraphqlFieldVisibility) GraphQLOutputType(graphql.schema.GraphQLOutputType) CompletableFuture(java.util.concurrent.CompletableFuture) GraphQLObjectType(graphql.schema.GraphQLObjectType) InstrumentationFieldFetchParameters(graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters)

Aggregations

DataFetchingEnvironment (graphql.schema.DataFetchingEnvironment)16 DataFetcher (graphql.schema.DataFetcher)12 List (java.util.List)9 Field (graphql.language.Field)7 Optional (java.util.Optional)7 Map (java.util.Map)6 Logger (org.slf4j.Logger)6 LoggerFactory (org.slf4j.LoggerFactory)6 Argument (graphql.language.Argument)5 Selection (graphql.language.Selection)5 Collectors (java.util.stream.Collectors)5 ArrayValue (graphql.language.ArrayValue)4 BooleanValue (graphql.language.BooleanValue)4 FloatValue (graphql.language.FloatValue)4 FragmentDefinition (graphql.language.FragmentDefinition)4 FragmentSpread (graphql.language.FragmentSpread)4 InlineFragment (graphql.language.InlineFragment)4 IntValue (graphql.language.IntValue)4 ObjectField (graphql.language.ObjectField)4 ObjectValue (graphql.language.ObjectValue)4