module Aws.DynamoDb.Commands.BatchGetItem where
import Control.Applicative
import Data.Aeson
import Data.Default
import qualified Data.HashMap.Strict as HM
import qualified Data.Text as T
import Prelude
import Aws.Core
import Aws.DynamoDb.Core
import Aws.DynamoDb.Commands.GetItem
data GetRequestItem = GetRequestItem{
griProjExpr :: Maybe T.Text
, griConsistent ::Bool
, griKeys :: [PrimaryKey]
} deriving (Eq,Show,Read,Ord)
data BatchGetItem = BatchGetItem {
bgRequests :: [(T.Text,GetRequestItem)]
, bgRetCons :: ReturnConsumption
} deriving (Eq,Show,Read,Ord)
batchGetRequestItem :: Maybe T.Text
-> Bool
-> [PrimaryKey]
-> GetRequestItem
batchGetRequestItem expr consistent keys = GetRequestItem expr consistent keys
toBatchGet :: [GetItem] -> BatchGetItem
toBatchGet gs = BatchGetItem (convert gs) def
where
groupItems :: [GetItem]-> HM.HashMap T.Text [GetItem] -> HM.HashMap T.Text [GetItem]
groupItems [] hm = hm
groupItems (x:xs) hm = let key = giTableName x
in groupItems xs (HM.insert key (x : (HM.lookupDefault [] key hm)) hm)
convert :: [GetItem] -> [(T.Text,GetRequestItem)]
convert gs' = let l = HM.toList $ groupItems gs' HM.empty
in map (\(table,items@(i:_)) ->(table,GetRequestItem
(T.intercalate "," <$> giAttrs i)
(giConsistent i)
(map giKey items)) ) l
batchGetItem :: [(T.Text, GetRequestItem)]
-> BatchGetItem
batchGetItem reqs = BatchGetItem reqs def
instance ToJSON GetRequestItem where
toJSON GetRequestItem{..} =
(object $ maybe [] (return . ("ProjectionExpression" .=)) griProjExpr ++
["ConsistentRead" .= griConsistent
, "Keys" .= griKeys])
instance ToJSON BatchGetItem where
toJSON BatchGetItem{..} =
object $
[ "RequestItems" .= HM.fromList bgRequests
, "ReturnConsumedCapacity" .= bgRetCons
]
instance FromJSON GetRequestItem where
parseJSON (Object p) = do
GetRequestItem <$> p .:? "ProjectionExpression"
<*> p .: "ConsistentRead"
<*> p .: "Keys"
parseJSON _ = fail "unable to parse GetRequestItem"
data BatchGetItemResponse = BatchGetItemResponse {
bgResponses :: [(T.Text, [Item])]
, bgUnprocessed :: Maybe [(T.Text,GetRequestItem)]
, bgConsumed :: Maybe ConsumedCapacity
} deriving (Eq,Show,Read,Ord)
instance Transaction BatchGetItem BatchGetItemResponse
instance SignQuery BatchGetItem where
type ServiceConfiguration BatchGetItem = DdbConfiguration
signQuery gi = ddbSignQuery "BatchGetItem" gi
instance FromJSON BatchGetItemResponse where
parseJSON (Object v) = BatchGetItemResponse
<$> (HM.toList <$> (v .: "Responses"))
<*> v .:? "UnprocessedItems"
<*> v .:? "ConsumedCapacity"
parseJSON _ = fail "BatchGetItemResponse must be an object."
instance ResponseConsumer r BatchGetItemResponse where
type ResponseMetadata BatchGetItemResponse = DdbResponse
responseConsumer _ _ ref resp = ddbResponseConsumer ref resp
instance AsMemoryResponse BatchGetItemResponse where
type MemoryResponse BatchGetItemResponse = BatchGetItemResponse
loadToMemory = return