2020-07-03 13:05:23 +02:00
package nouritsu ;
2020-07-04 00:38:18 +02:00
import io.vavr.collection.HashSet ;
2020-07-03 13:05:23 +02:00
import io.vavr.control.Either ;
2020-07-04 00:38:18 +02:00
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 ;
2020-07-03 13:05:23 +02:00
2020-07-04 00:38:18 +02:00
import java.util.function.Function ;
2020-07-03 13:05:23 +02:00
public class Dao {
2020-07-04 00:38:18 +02:00
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 ( ) ) ;
2020-07-03 13:05:23 +02:00
}
2020-07-04 00:38:18 +02:00
public Either < Resp , String > addStore ( Store store ) {
return Either . right ( " Registered new store “%s” with the sections [%s] " . formatted ( store . name ( ) , store . sections ( ) ) ) ;
2020-07-03 13:05:23 +02:00
}
}