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

Commit 76fbd25

Browse files
committed
feat: add SpringValueCache for easy creation of ValueCache that use Spring Caches
1 parent 8ef25cf commit 76fbd25

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package graphql.kickstart.spring.cache;
2+
3+
import static java.util.concurrent.CompletableFuture.runAsync;
4+
import static java.util.concurrent.CompletableFuture.supplyAsync;
5+
6+
import java.util.concurrent.CompletableFuture;
7+
import java.util.function.Function;
8+
import lombok.RequiredArgsConstructor;
9+
import org.dataloader.ValueCache;
10+
import org.springframework.cache.Cache;
11+
12+
/**
13+
* A {@link ValueCache} which uses a Spring {@link Cache} for caching.
14+
*
15+
* @see <a
16+
* href="https://www.graphql-java.com/documentation/batching/#per-request-data-loaders">GraphQL Java
17+
* docs</a>
18+
*/
19+
@RequiredArgsConstructor
20+
public class SpringValueCache<K, V> implements ValueCache<K, V> {
21+
22+
private final Cache cache;
23+
private Function<K, ?> keyTransformer;
24+
25+
@Override
26+
public CompletableFuture<V> get(K key) {
27+
return supplyAsync(() -> ((V) this.cache.get(this.getKey(key)).get()));
28+
}
29+
30+
@Override
31+
public CompletableFuture<V> set(K key, V value) {
32+
return supplyAsync(() -> {
33+
this.cache.put(this.getKey(key), value);
34+
return value;
35+
});
36+
}
37+
38+
@Override
39+
public CompletableFuture<Void> delete(K key) {
40+
return runAsync(() -> this.cache.evictIfPresent(this.getKey(key)));
41+
}
42+
43+
@Override
44+
public CompletableFuture<Void> clear() {
45+
return runAsync(this.cache::invalidate);
46+
}
47+
48+
public <KFinal> SpringValueCache<K, V> setKeyTransformer(Function<K, KFinal> transformer) {
49+
this.keyTransformer = transformer;
50+
return this;
51+
}
52+
53+
private Object getKey(K key) {
54+
return (
55+
this.keyTransformer == null
56+
? key
57+
: this.keyTransformer.apply(key)
58+
);
59+
}
60+
}

0 commit comments

Comments
 (0)