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

Commit e04fc1b

Browse files
committed
feat: added SpringValueCache for easy creation of data loader ValueCache objects that utilize Spring Caches under the hood
1 parent 8ef25cf commit e04fc1b

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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 lombok.RequiredArgsConstructor;
8+
import org.dataloader.ValueCache;
9+
import org.springframework.cache.Cache;
10+
11+
/**
12+
* A {@link ValueCache} which uses a Spring {@link Cache} for caching.
13+
*
14+
* @see <a href="https://www.graphql-java.com/documentation/batching/#per-request-data-loaders">GraphQL Java docs</a>
15+
*/
16+
@RequiredArgsConstructor
17+
public class SpringValueCache<K, V> implements ValueCache<K, V> {
18+
19+
private final Cache cache;
20+
21+
@Override
22+
public CompletableFuture<V> get(K key) {
23+
return supplyAsync(() -> ((V) this.cache.get(key).get()));
24+
}
25+
26+
@Override
27+
public CompletableFuture<V> set(K key, V value) {
28+
return supplyAsync(() -> {
29+
this.cache.put(key, value);
30+
return value;
31+
});
32+
}
33+
34+
@Override
35+
public CompletableFuture<Void> delete(K key) {
36+
return runAsync(() -> this.cache.evictIfPresent(key));
37+
}
38+
39+
@Override
40+
public CompletableFuture<Void> clear() {
41+
return runAsync(this.cache::invalidate);
42+
}
43+
}

0 commit comments

Comments
 (0)