Skip to content

Instantly share code, notes, and snippets.

@mmakowski
Last active August 29, 2015 14:04
Show Gist options
  • Save mmakowski/c511efbb9aa0dafa84ad to your computer and use it in GitHub Desktop.
Save mmakowski/c511efbb9aa0dafa84ad to your computer and use it in GitHub Desktop.
EventSourcing1
module EventSourcing where
import Control.Monad.State
data Command = CreateToDoItemCommand { cmdTodoId :: String, cmdDescription :: String }
| MarkCompletedCommand { cmdTodoId :: String }
deriving (Eq, Ord, Show)
data Event = ToDoItemCreatedEvent { evtTodoId :: String, evtDescription :: String }
| ToDoItemCompletedEvent { evtTodoId :: String }
deriving (Eq, Ord, Show)
type Store = [Event]
type EventSourced = State Store
dispatch :: Command -> EventSourced [Event]
dispatch cmd = do
store <- get
let events = dispatch' cmd store
put (store ++ events)
return events
dispatch' :: Command -> Store -> [Event]
dispatch' (CreateToDoItemCommand i desc) _ = [ToDoItemCreatedEvent i desc]
dispatch' (MarkCompletedCommand i) _ = [ToDoItemCompletedEvent i]
runEventSourced :: EventSourced a -> a
runEventSourced s = evalState s []
thenDispatch :: EventSourced [Event] -> Command -> EventSourced [Event]
thenDispatch es cmd = do
events1 <- es
events2 <- dispatch cmd
return (events1 ++ events2)
test :: [Event]
test = runEventSourced $
dispatch (CreateToDoItemCommand "1" "example")
`thenDispatch` CreateToDoItemCommand "2" "another"
`thenDispatch` MarkCompletedCommand "1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment