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 withRedis(Function 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> 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 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 addStore(Store store) { return Either.right("Registered new store “%s” with the sections [%s]".formatted(store.name(), store.sections())); } }