diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/cache/SpringValueCache.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/cache/SpringValueCache.java new file mode 100644 index 00000000..0521c935 --- /dev/null +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/cache/SpringValueCache.java @@ -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 GraphQL Java docs + */ +@RequiredArgsConstructor +public class SpringValueCache implements ValueCache { + + private final Cache cache; + + @Override + public CompletableFuture get(K key) { + return supplyAsync(() -> ((V) this.cache.get(key).get())); + } + + @Override + public CompletableFuture set(K key, V value) { + return supplyAsync(() -> { + this.cache.put(key, value); + return value; + }); + } + + @Override + public CompletableFuture delete(K key) { + return runAsync(() -> this.cache.evictIfPresent(key)); + } + + @Override + public CompletableFuture clear() { + return runAsync(this.cache::invalidate); + } +}