Last active
April 8, 2021 05:38
-
-
Save ialeke/1995cabd5e7b2e4fe30537a03310113c to your computer and use it in GitHub Desktop.
Jason.Encoder ecto example, removing __meta__ and %Ecto.Association.NotLoaded{}
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
defimpl Jason.Encoder, for: [Example.Module1, Example.Module2] do | |
def encode(value, opts) do | |
value | |
|> process_for_json | |
|> Jason.Encode.map(opts) | |
end | |
def remove_unloaded({_field, %Ecto.Association.NotLoaded{}}, accum), do: accum | |
def remove_unloaded({key, %_{__meta__: _} = data_map}, accum) do | |
accum |> Keyword.put(key, process_for_json(data_map)) | |
end | |
def remove_unloaded(field, accum), do: accum ++ [field] | |
def process_for_json(data) do | |
data | |
|> Map.from_struct() | |
|> Map.delete(:__meta__) | |
|> Enum.into([]) | |
|> Enum.reduce([], &remove_unloaded/2) | |
|> Enum.into(%{}) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment