Skip to content

Instantly share code, notes, and snippets.

@trbngr
Last active June 7, 2023 16:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save trbngr/278405d4820863edbf90acea1afb3ca9 to your computer and use it in GitHub Desktop.
Save trbngr/278405d4820863edbf90acea1afb3ca9 to your computer and use it in GitHub Desktop.
defmodule EventStore.CategoryStreamLinker do
@moduledoc """
Links streams from aggregate instances to their respective category streams.
example: events from stream_uuid of `contractors_contract-07c52787-da0c-444f-9783-5d380f7093f9` will be
linked to stream_uuid of `contractors_contract`.
"""
use Commanded.Event.Handler,
application: My.App,
name: __MODULE__
@default_opts [enabled: true]
def handle(_event, metadata) do
:my_app
|> Application.get_env(:category_projections, @default_opts)
|> Keyword.merge(@default_opts, fn _key, left, _right -> left end)
|> Enum.into(%{})
|> link_to_category(metadata)
:ok
end
defp link_to_category(%{enabled: true}, %{stream_id: stream_id, event_id: event_id}) do
stream_id
|> String.split("-")
|> link_to_category(event_id)
end
defp link_to_category([category | _], event_id) do
MyApp.EventStore.link_to_stream(category, :any_version, [event_id])
end
defp link_to_category(_, _), do: nil
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment