Data Loaders are a popular caching pattern from the JavaScript GraphQL implementation.
Since graphql-java
provides support for this pattern
using the DataLoader
and DataLoaderRegistry.
graphql-kotlin
provides support for DataLoaders
with this graphql-kotlin-dataloader
module through common interfaces.
To help in the registration of DataLoaders
, we have created a basic interface KotlinDataLoader
:
interface KotlinDataLoader<K, V> {
val dataLoaderName: String
fun getDataLoader(graphQLContext: GraphQLContext): DataLoader<K, V>
}
This allows for library users to still have full control over the creation of the DataLoader and its various configuration options.
class UserDataLoader : KotlinDataLoader<ID, User> {
override val dataLoaderName = "UserDataLoader"
override fun getDataLoader(graphQLContext: GraphQLContext) =
DataLoaderFactory.newDataLoader<ID, User>(
{ ids, batchLoaderEnvironment ->
val context = batchLoaderEnvironment.getContext<GraphQLContext>()
// do something with graphQLContext
CompletableFuture.supplyAsync {
ids.map { id -> userService.getUser(id) }
}
},
DataLoaderOptions.newOptions()
.setCachingEnabled(false)
.setBatchLoaderContextProvider { graphQLContext }
)
}
Factory that facilitates the instantiation of a KotlinDataLoaderRegistry which is just
a decorator of the original graphql-java
DataLoaderRegistry.
with the addition of allowing access to the state of the CacheMap
(futures cache) of each DataLoader
in order to know
all futures state.
Using a JVM dependency manager, link graphql-kotlin-dataloader
to your project.
With Maven:
<dependency>
<groupId>com.expediagroup</groupId>
<artifactId>graphql-kotlin-dataloader</artifactId>
<version>${latestVersion}</version>
</dependency>
With Gradle (example using kts):
implementation("com.expediagroup:graphql-kotlin-dataloader:$latestVersion")
Use KotlinDataLoaderRegistryFactory
val kotlinDataLoaderRegistry = KotlinDataLoaderRegistryFactory(
UserDataLoader()
).generate(graphQLContext)
val executionInput = ExecutionInput.newExecutionInput()
.query("query MyAwesomeQuery { foo { bar } }")
.dataLoaderRegistry(kotlinDataLoaderRegistry)
.build()
val result = graphQL.executeAsync(executionInput)
Additional information can be found in our documentation and the Javadocs of all published library versions.
If you have a question about something you can not find in our documentation or javadocs, feel free to start a new discussion.