Skip to content

Instantly share code, notes, and snippets.

@slashdotdash
Last active December 6, 2019 14:49
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 slashdotdash/d28feba38469604ea3346b257bfda73d to your computer and use it in GitHub Desktop.
Save slashdotdash/d28feba38469604ea3346b257bfda73d to your computer and use it in GitHub Desktop.
Commanded jsonb serializer with decode support
defmodule JsonbSerializer do
@moduledoc """
Serialize to/from PostgreSQL's native `jsonb` format.
"""
@behaviour EventStore.Serializer
alias Commanded.EventStore.TypeProvider
alias Commanded.Serialization.JsonDecoder
def serialize(%_{} = term) do
for {key, value} <- Map.from_struct(term), into: %{} do
{Atom.to_string(key), value}
end
end
def serialize(term), do: term
def deserialize(term, config) do
case Keyword.get(config, :type) do
nil ->
term
type ->
type
|> TypeProvider.to_struct()
|> to_struct(term)
|> JsonDecoder.decode()
end
end
def to_struct(type, term) do
struct(type, keys_to_atoms(term))
end
defp keys_to_atoms(map) when is_map(map) do
for {key, value} <- map, into: %{} do
{String.to_atom(key), keys_to_atoms(value)}
end
end
defp keys_to_atoms(value), do: value
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment