From 76fbd2548965a94f81ee1f6976ecf035db72e2d6 Mon Sep 17 00:00:00 2001 From: Brandon Sara Date: Mon, 21 Aug 2023 13:07:29 -0600 Subject: [PATCH] feat: add SpringValueCache for easy creation of ValueCache that use Spring Caches --- .../spring/cache/SpringValueCache.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/cache/SpringValueCache.java 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..0de7ed8b --- /dev/null +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/cache/SpringValueCache.java @@ -0,0 +1,60 @@ +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 java.util.function.Function; +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; + private Function keyTransformer; + + @Override + public CompletableFuture get(K key) { + return supplyAsync(() -> ((V) this.cache.get(this.getKey(key)).get())); + } + + @Override + public CompletableFuture set(K key, V value) { + return supplyAsync(() -> { + this.cache.put(this.getKey(key), value); + return value; + }); + } + + @Override + public CompletableFuture delete(K key) { + return runAsync(() -> this.cache.evictIfPresent(this.getKey(key))); + } + + @Override + public CompletableFuture clear() { + return runAsync(this.cache::invalidate); + } + + public SpringValueCache setKeyTransformer(Function transformer) { + this.keyTransformer = transformer; + return this; + } + + private Object getKey(K key) { + return ( + this.keyTransformer == null + ? key + : this.keyTransformer.apply(key) + ); + } +}