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);
}
};
}
Aggregations