Search in sources :

Example 6 with DataFetcher

use of graphql.schema.DataFetcher 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 7 with DataFetcher

use of graphql.schema.DataFetcher 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 8 with DataFetcher

use of graphql.schema.DataFetcher 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 9 with DataFetcher

use of graphql.schema.DataFetcher 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 10 with DataFetcher

use of graphql.schema.DataFetcher in project ontrack by nemerosa.

the class GQLRootQueryBuilds method buildFetcher.

private DataFetcher buildFetcher() {
    return environment -> {
        Integer id = environment.getArgument("id");
        Optional<String> oProject = GraphqlUtils.getStringArgument(environment, PROJECT_ARGUMENT);
        Optional<String> oBranch = GraphqlUtils.getStringArgument(environment, BRANCH_ARGUMENT);
        Object branchFilter = environment.getArgument(BUILD_BRANCH_FILTER_ARGUMENT);
        Object projectFilter = environment.getArgument(BUILD_PROJECT_FILTER_ARGUMENT);
        // Per ID
        if (id != null) {
            checkArgList(environment, "id");
            return Collections.singletonList(structureService.getBuild(ID.of(id)));
        } else // Per project
        if (oProject.isPresent()) {
            // ... and branch
            if (oBranch.isPresent()) {
                // Gets the branch
                Branch branch = structureService.findBranchByName(oProject.get(), oBranch.get()).orElseThrow(() -> new BranchNotFoundException(oProject.get(), oBranch.get()));
                // Configurable branch filter
                BuildFilterProviderData<?> filter = inputBuildStandardFilter.convert(branchFilter);
                // Runs the filter
                return filter.filterBranchBuilds(branch);
            } else // Project only
            {
                // Gets the project
                Project project = structureService.findProjectByName(oProject.get()).orElseThrow(() -> new ProjectNotFoundException(oProject.get()));
                // Build search form as argument
                BuildSearchForm form = inputBuildSearchForm.convert(projectFilter);
                return structureService.buildSearch(project.getId(), form);
            }
        } else // Branch filter only - not accepted
        if (branchFilter != null) {
            throw new IllegalStateException(String.format("%s must be used together with %s", BUILD_BRANCH_FILTER_ARGUMENT, BRANCH_ARGUMENT));
        } else // Project filter only - not accepted
        if (projectFilter != null) {
            throw new IllegalStateException(String.format("%s must be used together with %s", BUILD_PROJECT_FILTER_ARGUMENT, PROJECT_ARGUMENT));
        } else // None
        {
            return Collections.emptyList();
        }
    };
}
Also used : GraphQLString(graphql.Scalars.GraphQLString) ProjectNotFoundException(net.nemerosa.ontrack.model.exceptions.ProjectNotFoundException) GraphQLFieldDefinition(graphql.schema.GraphQLFieldDefinition) BuildFilterProviderData(net.nemerosa.ontrack.model.buildfilter.BuildFilterProviderData) Autowired(org.springframework.beans.factory.annotation.Autowired) GraphQLArgument.newArgument(graphql.schema.GraphQLArgument.newArgument) GraphqlUtils.stdList(net.nemerosa.ontrack.graphql.support.GraphqlUtils.stdList) GraphQLFieldDefinition.newFieldDefinition(graphql.schema.GraphQLFieldDefinition.newFieldDefinition) GraphqlUtils.checkArgList(net.nemerosa.ontrack.graphql.support.GraphqlUtils.checkArgList) Component(org.springframework.stereotype.Component) net.nemerosa.ontrack.model.structure(net.nemerosa.ontrack.model.structure) DataFetcher(graphql.schema.DataFetcher) Optional(java.util.Optional) GraphQLInt(graphql.Scalars.GraphQLInt) Collections(java.util.Collections) GraphqlUtils(net.nemerosa.ontrack.graphql.support.GraphqlUtils) BranchNotFoundException(net.nemerosa.ontrack.model.exceptions.BranchNotFoundException) ProjectNotFoundException(net.nemerosa.ontrack.model.exceptions.ProjectNotFoundException) Optional(java.util.Optional) BranchNotFoundException(net.nemerosa.ontrack.model.exceptions.BranchNotFoundException)

Aggregations

DataFetcher (graphql.schema.DataFetcher)10 DataFetchingEnvironment (graphql.schema.DataFetchingEnvironment)7 List (java.util.List)5 GraphQLString (graphql.Scalars.GraphQLString)4 GraphQLObjectType (graphql.schema.GraphQLObjectType)4 ArrayList (java.util.ArrayList)4 ExecutionResult (graphql.ExecutionResult)3 GraphQLFieldDefinition (graphql.schema.GraphQLFieldDefinition)3 GraphQLSchema (graphql.schema.GraphQLSchema)3 Map (java.util.Map)3 Optional (java.util.Optional)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 ExecutionInput (graphql.ExecutionInput)2 GraphQL (graphql.GraphQL)2 GraphQLInt (graphql.Scalars.GraphQLInt)2 Instrumentation (graphql.execution.instrumentation.Instrumentation)2 DataLoaderDispatcherInstrumentation (graphql.execution.instrumentation.dataloader.DataLoaderDispatcherInstrumentation)2 GraphQLFieldDefinition.newFieldDefinition (graphql.schema.GraphQLFieldDefinition.newFieldDefinition)2 GraphQLList (graphql.schema.GraphQLList)2 GraphQLObjectType.newObject (graphql.schema.GraphQLObjectType.newObject)2