Skip to content
This repository has been archived by the owner on Dec 19, 2023. It is now read-only.

Commit

Permalink
added SpringValueCache for easy creation of data loader ValueCache ob…
Browse files Browse the repository at this point in the history
…jects that utilize Spring Caches under the hood
  • Loading branch information
bsara committed Aug 21, 2023
1 parent 8ef25cf commit 59dd387
Showing 1 changed file with 43 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package graphql.kickstart.spring.cache;

import static java.util.concurrent.CompletableFuture.runAsync;
import static java.util.concurrent.CompletableFuture.supplyAsync;

import java.util.concurrent.CompletableFuture;
import lombok.RequiredArgsConstructor;
import org.dataloader.ValueCache;
import org.springframework.cache.Cache;

/**
* A {@link ValueCache} which uses a Spring {@link Cache} for caching.
*
* @see <a href="https://www.graphql-java.com/documentation/batching/#per-request-data-loaders">GraphQL Java docs</a>
*/
@RequiredArgsConstructor
public class SpringValueCache<K, V> implements ValueCache<K, V> {

private final Cache cache;

@Override
public CompletableFuture<V> get(K key) {
return supplyAsync(() -> ((V) this.cache.get(key).get()));
}

@Override
public CompletableFuture<V> set(K key, V value) {
return supplyAsync(() -> {
this.cache.put(key, value);
return value;
});
}

@Override
public CompletableFuture<Void> delete(K key) {
return runAsync(() -> this.cache.evictIfPresent(key));
}

@Override
public CompletableFuture<Void> clear() {
return runAsync(this.cache::invalidate);
}
}

0 comments on commit 59dd387

Please sign in to comment.