Search in sources :

Example 1 with BatchLoaderEnvironment

use of org.dataloader.BatchLoaderEnvironment in project graphql-java by graphql-java.

the class DataLoaderBatchingExamples method passingContextToYourBatchLoader.

private void passingContextToYourBatchLoader() {
    BatchLoaderWithContext<String, Object> batchLoaderWithCtx = new BatchLoaderWithContext<String, Object>() {

        @Override
        public CompletionStage<List<Object>> load(List<String> keys, BatchLoaderEnvironment loaderContext) {
            // 
            // we can have an overall context object
            SecurityContext securityCtx = loaderContext.getContext();
            // 
            // and we can have a per key set of context objects
            Map<Object, Object> keysToSourceObjects = loaderContext.getKeyContexts();
            return CompletableFuture.supplyAsync(() -> getTheseCharacters(securityCtx.getToken(), keys, keysToSourceObjects));
        }
    };
    // ....
    SecurityContext securityCtx = SecurityContext.newSecurityContext();
    BatchLoaderContextProvider contextProvider = new BatchLoaderContextProvider() {

        @Override
        public Object getContext() {
            return securityCtx;
        }
    };
    // 
    // this creates an overall context for the dataloader
    // 
    DataLoaderOptions loaderOptions = DataLoaderOptions.newOptions().setBatchLoaderContextProvider(contextProvider);
    DataLoader<String, Object> characterDataLoader = DataLoaderFactory.newDataLoader(batchLoaderWithCtx, loaderOptions);
    // .... later in your data fetcher
    DataFetcher<?> dataFetcherThatCallsTheDataLoader = new DataFetcher<Object>() {

        @Override
        public Object get(DataFetchingEnvironment environment) {
            String argId = environment.getArgument("id");
            Object source = environment.getSource();
            // 
            return characterDataLoader.load(argId, source);
        }
    };
}
Also used : DataLoaderOptions(org.dataloader.DataLoaderOptions) BatchLoaderContextProvider(org.dataloader.BatchLoaderContextProvider) BatchLoaderWithContext(org.dataloader.BatchLoaderWithContext) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) BatchLoaderEnvironment(org.dataloader.BatchLoaderEnvironment) List(java.util.List) DataFetcher(graphql.schema.DataFetcher)

Aggregations

DataFetcher (graphql.schema.DataFetcher)1 DataFetchingEnvironment (graphql.schema.DataFetchingEnvironment)1 List (java.util.List)1 BatchLoaderContextProvider (org.dataloader.BatchLoaderContextProvider)1 BatchLoaderEnvironment (org.dataloader.BatchLoaderEnvironment)1 BatchLoaderWithContext (org.dataloader.BatchLoaderWithContext)1 DataLoaderOptions (org.dataloader.DataLoaderOptions)1