Last active
December 6, 2019 14:49
-
-
Save slashdotdash/d28feba38469604ea3346b257bfda73d to your computer and use it in GitHub Desktop.
Commanded jsonb serializer with decode support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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