Skip to content

Instantly share code, notes, and snippets.

@slashdotdash
Last active August 15, 2018 12:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save slashdotdash/01cd1d03e99b970798c8993c0a19ec59 to your computer and use it in GitHub Desktop.
Save slashdotdash/01cd1d03e99b970798c8993c0a19ec59 to your computer and use it in GitHub Desktop.
Commanded multi-entity aggregates
defmodule Article do
defstruct [:content, comments: []]
# public commands
def execute(%Article{}, %PublishArticle{content: content}) do
%ArticlePublished{content: content}
end
def execute(%Article{}, %CommentOnArticle{} = comment) do
Comment.new() |> Comment.execute(comment)
end
# state mutators
def apply(%Article{}, %ArticlePublished{content: content}) do
%Article{content: content}
end
def apply(%Article{comments: comments} = article %ArticleCommented{} = commented) do
comment = Comment.new() |> Comment.apply(commented)
%Article{article |
comments: [comment | comments]
}
end
end
defmodule Comment do
defstruct [:comment]
def new, do: %Comment{}
def execute(%Comment{}, %CommentOnArticle{comment: comment}) do
%ArticleCommented{comment: comment}
end
def apply(%Comment{}, %ArticleCommented{comment: comment}) do
%Comment{comment: comment}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment