module Aggregates ( Project(..) , ProjectId , Task(..) , TaskId ) where import Control.Monad (liftM) import Data.CQRS (Aggregate(..), GUID) import Data.Default (Default(..)) import Data.Serialize (Serialize(..), decode, encode) import Data.Text (Text) import Data.Text.Encoding (decodeUtf8, encodeUtf8) import Data.Typeable (Typeable) import Data.Word (Word8) -- Projects. type ProjectId = GUID Project data Project = DefaultProject | ActiveProject { projectName :: Text } deriving (Typeable) instance Serialize Project where put DefaultProject = do put (0 :: Word8) put (ActiveProject pn) = do put (1 :: Word8) put $ encodeUtf8 pn get = do i :: Word8 <- get case i of 0 -> return DefaultProject 1 -> do pn <- liftM decodeUtf8 get return $ ActiveProject pn _ -> fail $ "Cannot decode project state" ++ show i instance Aggregate Project where encodeAggregate = encode decodeAggregate s = case decode s of Left e -> error e Right a -> a instance Default Project where def = DefaultProject -- Tasks. type TaskId = GUID Task data Task = NewTask | ActiveTask { taskProjectId :: ProjectId , taskShortDescription :: Text } deriving (Typeable) instance Serialize Task where put NewTask = do put (0 :: Word8) put (ActiveTask tpid tsd) = do put (1 :: Word8) put tpid put $ encodeUtf8 tsd get = do i :: Word8 <- get case i of 0 -> return NewTask 1 -> do tpid <- get tsd <- liftM decodeUtf8 get return $ ActiveTask tpid tsd _ -> fail $ "Cannot decode task state: " ++ show i instance Aggregate Task where encodeAggregate = encode decodeAggregate s = case decode s of Left e -> error e Right a -> a instance Default Task where def = NewTask