55 lines
1.6 KiB
Java
55 lines
1.6 KiB
Java
package nouritsu;
|
|
|
|
import io.vavr.collection.HashSet;
|
|
import io.vavr.control.Either;
|
|
import nouritsu.types.Resp;
|
|
import nouritsu.types.Section;
|
|
import nouritsu.types.ShoppingItem;
|
|
import nouritsu.types.Store;
|
|
import redis.clients.jedis.Jedis;
|
|
import redis.clients.jedis.JedisPool;
|
|
|
|
import java.util.function.Function;
|
|
|
|
public class Dao {
|
|
private final JedisPool pool;
|
|
|
|
Dao() {
|
|
pool = new JedisPool();
|
|
}
|
|
|
|
private <T> T withRedis(Function<Jedis, T> f) {
|
|
try (var redis = pool.getResource()) {
|
|
return f.apply(redis);
|
|
}
|
|
}
|
|
|
|
public String clearList(String id) {
|
|
withRedis(redis -> redis.del(id));
|
|
// Just always return okay, even if we didn’t have data to begin with.
|
|
// Idempotency yay \o/
|
|
return "Cleared list of user “%s“".formatted(id);
|
|
}
|
|
|
|
public Either<Resp, HashSet<ShoppingItem>> getList(String id) {
|
|
return withRedis(redis ->
|
|
redis.exists(id)
|
|
? Either.right(HashSet.ofAll(redis.smembers(id)).map(s -> new ShoppingItem(s, Section.CANS)))
|
|
: Either.left(Resp.NOT_FOUND.apply("No list found for user “%s”".formatted(id)))
|
|
);
|
|
}
|
|
|
|
public Either<Resp, String> addToList(String id, String item) {
|
|
return Either.right("Added “%s“ to list of user “%s”".formatted(item, id));
|
|
}
|
|
|
|
public String addItem(ShoppingItem item) {
|
|
return "Registered new item “%s” under the section “%s”"
|
|
.formatted(item.name(), item.section().name().toLowerCase());
|
|
}
|
|
|
|
public Either<Resp, String> addStore(Store store) {
|
|
return Either.right("Registered new store “%s” with the sections [%s]".formatted(store.name(), store.sections()));
|
|
}
|
|
}
|