org.rapidgraphql.dataloaders.GuavaValueCache Maven / Gradle / Ivy
package org.rapidgraphql.dataloaders;
import com.google.common.cache.Cache;
import org.dataloader.ValueCache;
import java.util.concurrent.CompletableFuture;
public class GuavaValueCache implements ValueCache {
public static class EntityNotFoundException extends RuntimeException {
}
private final Cache cache;
private final EntityNotFoundException defaultException = new EntityNotFoundException();
public GuavaValueCache(Cache cache) {
this.cache = cache;
}
@Override
public CompletableFuture get(K key) {
V value = cache.getIfPresent(key);
return value==null ?
CompletableFuture.failedFuture(defaultException)
: CompletableFuture.completedFuture(value);
}
@Override
public CompletableFuture set(K key, V value) {
cache.put(key, value);
return CompletableFuture.completedFuture(value);
}
@Override
public CompletableFuture delete(K key) {
cache.invalidate(key);
return CompletableFuture.completedFuture(null);
}
@Override
public CompletableFuture clear() {
cache.invalidateAll();
return CompletableFuture.completedFuture(null);
}
}