Skip to content

Instantly share code, notes, and snippets.

@Trevoke
Forked from slashdotdash/article.ex
Created January 23, 2018 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Trevoke/4df7091bda0cff27fc2b83d35764e845 to your computer and use it in GitHub Desktop.
Save Trevoke/4df7091bda0cff27fc2b83d35764e845 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