The following code runs a mget command with Hedis, and return the result as a [Maybe BS.ByteString]:
-- | Text to ByteString
tbs :: Text -> BS.ByteString
tbs = BS.pack . T.unpack
-- | ByteString to Text
bst :: BS.ByteString -> Text
bst = T.pack . BS.unpack
mgetRedis :: Redis.Connection -> [Text] -> IO [Maybe BS.ByteString]
mgetRedis connection keys =
runRedis connection action
where
action = do
result <- Redis.mget $ tbs <$> keys
-- `result` is of type `Either Reply [Maybe BS.ByteString]`
case result of
Right values -> pure values
_ -> pure []
First of all, I find this code quite messy and was wondering if there was any way to make it cleaner.
Second, I'd like mgetRedis to return a [Maybe Text] instead, using the bst helper written above. I can't do pure $ bst <$> values because there are two levels of unpacking here: first, the Maybe and then the List. Is there any way that this function could return the desired type without drowning in a sea of nested case statements?
T.pack . BS.unpackis almost certainly bad idea. Not only it's slow (because of the intermediate list, though the compiler might fuse that away), it also disregards any encoding issues. Thetextpackage offers dedicated encoders that make this explicit. Also I find it dubious to return an empty list if the request has failed (?). - leftaroundaboutEitherall the way down to the business logic code where the response will be processed? - Jivan