Search in sources :

Example 11 with DataFetchingEnvironment

use of graphql.schema.DataFetchingEnvironment in project graphql-java by graphql-java.

the class BatchingExamples method starWarsExample.

void starWarsExample() {
    // a batch loader function that will be called with N or more keys for batch loading
    BatchLoader<String, Object> characterBatchLoader = new BatchLoader<String, Object>() {

        @Override
        public CompletionStage<List<Object>> load(List<String> keys) {
            // 
            return CompletableFuture.supplyAsync(() -> getCharacterDataViaBatchHTTPApi(keys));
        }
    };
    // a data loader for characters that points to the character batch loader
    DataLoader<String, Object> characterDataLoader = new DataLoader<>(characterBatchLoader);
    // 
    // use this data loader in the data fetchers associated with characters and put them into
    // the graphql schema (not shown)
    // 
    DataFetcher heroDataFetcher = new DataFetcher() {

        @Override
        public Object get(DataFetchingEnvironment environment) {
            // R2D2
            return characterDataLoader.load("2001");
        }
    };
    DataFetcher friendsDataFetcher = new DataFetcher() {

        @Override
        public Object get(DataFetchingEnvironment environment) {
            StarWarsCharacter starWarsCharacter = environment.getSource();
            List<String> friendIds = starWarsCharacter.getFriendIds();
            return characterDataLoader.loadMany(friendIds);
        }
    };
    // 
    // DataLoaderRegistry is a place to register all data loaders in that needs to be dispatched together
    // in this case there is 1 but you can have many
    // 
    DataLoaderRegistry registry = new DataLoaderRegistry();
    registry.register("character", characterDataLoader);
    // 
    // this instrumentation implementation will dispatched all the dataloaders
    // as each level fo the graphql query is executed and hence make batched objects
    // available to the query and the associated DataFetchers
    // 
    DataLoaderDispatcherInstrumentation dispatcherInstrumentation = new DataLoaderDispatcherInstrumentation(registry);
    // 
    // now build your graphql object and execute queries on it.
    // the data loader will be invoked via the data fetchers on the
    // schema fields
    // 
    GraphQL graphQL = GraphQL.newGraphQL(buildSchema()).instrumentation(dispatcherInstrumentation).build();
}
Also used : GraphQL(graphql.GraphQL) DataLoaderDispatcherInstrumentation(graphql.execution.instrumentation.dataloader.DataLoaderDispatcherInstrumentation) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) BatchLoader(org.dataloader.BatchLoader) DataLoader(org.dataloader.DataLoader) DataLoaderRegistry(org.dataloader.DataLoaderRegistry) List(java.util.List) DataFetcher(graphql.schema.DataFetcher)

Example 12 with DataFetchingEnvironment

use of graphql.schema.DataFetchingEnvironment in project graphql-java by graphql-java.

the class ConcernsExamples method contextHelper.

private void contextHelper() {
    // 
    // this could be code that authorises the user in some way and sets up enough context
    // that can be used later inside data fetchers allowing them
    // to do their job
    // 
    UserContext contextForUser = YourGraphqlContextBuilder.getContextForUser(getCurrentUser());
    ExecutionInput executionInput = ExecutionInput.newExecutionInput().context(contextForUser).build();
    ExecutionResult executionResult = graphQL.execute(executionInput);
    // ...
    // 
    // later you are able to use this context object when a data fetcher is invoked
    // 
    DataFetcher dataFetcher = new DataFetcher() {

        @Override
        public Object get(DataFetchingEnvironment environment) {
            UserContext userCtx = environment.getContext();
            Long businessObjId = environment.getArgument("businessObjId");
            return invokeBusinessLayerMethod(userCtx, businessObjId);
        }
    };
}
Also used : ExecutionResult(graphql.ExecutionResult) ExecutionInput(graphql.ExecutionInput) DataFetcher(graphql.schema.DataFetcher) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment)

Example 13 with DataFetchingEnvironment

use of graphql.schema.DataFetchingEnvironment in project graphql-java by graphql-java.

the class MappingExamples method productsDataFetcher.

void productsDataFetcher() {
    DataFetcher productsDataFetcher = new DataFetcher() {

        @Override
        public Object get(DataFetchingEnvironment env) {
            String matchArg = env.getArgument("match");
            List<ProductInfo> productInfo = getMatchingProducts(matchArg);
            List<ProductCostInfo> productCostInfo = getProductCosts(productInfo);
            List<ProductTaxInfo> productTaxInfo = getProductTax(productInfo);
            return mapDataTogether(productInfo, productCostInfo, productTaxInfo);
        }
    };
}
Also used : DataFetcher(graphql.schema.DataFetcher) PropertyDataFetcher(graphql.schema.PropertyDataFetcher) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment)

Example 14 with DataFetchingEnvironment

use of graphql.schema.DataFetchingEnvironment in project graphql-java by graphql-java.

the class ReadmeExamples method dataFetching.

void dataFetching() {
    DataFetcher<Foo> fooDataFetcher = new DataFetcher<Foo>() {

        @Override
        public Foo get(DataFetchingEnvironment environment) {
            // environment.getSource() is the value of the surrounding
            // object. In this case described by objectType
            // Perhaps getting from a DB or whatever
            Foo value = perhapsFromDatabase();
            return value;
        }
    };
    GraphQLObjectType objectType = newObject().name("ObjectType").field(newFieldDefinition().name("foo").type(GraphQLString).dataFetcher(fooDataFetcher)).build();
}
Also used : GraphQLObjectType(graphql.schema.GraphQLObjectType) StaticDataFetcher(graphql.schema.StaticDataFetcher) DataFetcher(graphql.schema.DataFetcher) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment)

Example 15 with DataFetchingEnvironment

use of graphql.schema.DataFetchingEnvironment in project engine by craftercms.

the class ContentTypeBasedDataFetcher method addFieldFilterFromObjectField.

protected void addFieldFilterFromObjectField(String path, ObjectField filter, BoolQueryBuilder query, DataFetchingEnvironment env) {
    boolean isVariable = filter.getValue() instanceof VariableReference;
    switch(filter.getName()) {
        case ARG_NAME_NOT:
            BoolQueryBuilder notQuery = boolQuery();
            if (isVariable) {
                ((List<Map<String, Object>>) env.getVariables().get(((VariableReference) filter.getValue()).getName())).forEach(notFilter -> notFilter.entrySet().forEach(entry -> addFieldFilterFromMapEntry(path, entry, notQuery, env)));
            } else {
                ((ArrayValue) filter.getValue()).getValues().forEach(notFilter -> ((ObjectValue) notFilter).getObjectFields().forEach(notField -> addFieldFilterFromObjectField(path, notField, notQuery, env)));
            }
            if (!notQuery.filter().isEmpty()) {
                notQuery.filter().forEach(query::mustNot);
            }
            break;
        case ARG_NAME_AND:
            if (isVariable) {
                ((List<Map<String, Object>>) env.getVariables().get(((VariableReference) filter.getValue()).getName())).forEach(andFilter -> andFilter.entrySet().forEach(entry -> addFieldFilterFromMapEntry(path, entry, query, env)));
            } else {
                ((ArrayValue) filter.getValue()).getValues().forEach(andFilter -> ((ObjectValue) andFilter).getObjectFields().forEach(andField -> addFieldFilterFromObjectField(path, andField, query, env)));
            }
            break;
        case ARG_NAME_OR:
            BoolQueryBuilder tempQuery = boolQuery();
            if (isVariable) {
                ((List<Map<String, Object>>) env.getVariables().get(((VariableReference) filter.getValue()).getName())).forEach(orFilter -> orFilter.entrySet().forEach(entry -> addFieldFilterFromMapEntry(path, entry, tempQuery, env)));
            } else {
                ((ArrayValue) filter.getValue()).getValues().forEach(orFilter -> ((ObjectValue) orFilter).getObjectFields().forEach(orField -> addFieldFilterFromObjectField(path, orField, tempQuery, env)));
            }
            if (!tempQuery.filter().isEmpty()) {
                BoolQueryBuilder orQuery = boolQuery();
                tempQuery.filter().forEach(orQuery::should);
                query.filter(boolQuery().must(orQuery));
            }
            break;
        default:
            QueryBuilder builder = getFilterQueryFromObjectField(path, filter, env);
            if (builder != null) {
                query.filter(builder);
            }
    }
}
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) ObjectValue(graphql.language.ObjectValue) VariableReference(graphql.language.VariableReference) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) LinkedList(java.util.LinkedList) List(java.util.List) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder)

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