Created
September 1, 2017 06:30
-
-
Save bbakerman/1101b3b577cbaaae2cb45ee46ecf2aa0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) { | |
// | |
// we use supplyAsync() of values here for maximum parellisation | |
// | |
return CompletableFuture.supplyAsync(() -> getCharacterDataViaBatchHTTPApi(keys)); | |
} | |
}; | |
// a data loader for characters that points to the character batch loader | |
DataLoader characterDataLoader = new DataLoader<String, Object>(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) { | |
return characterDataLoader.load("2001"); // R2D2 | |
} | |
}; | |
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(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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment