Created
October 12, 2021 20:09
-
-
Save heyitsjames/3bf9739d18a4bb95989b864a118f510a to your computer and use it in GitHub Desktop.
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 MyApp.Encoder do | |
@moduledoc """ | |
General implementation for the Jason encoder to be used in Ecto schemas | |
""" | |
defmacro __using__(opts) do | |
drop_fields = Keyword.get(opts, :drop, []) | |
quote do | |
defimpl Jason.Encoder, for: [__MODULE__] do | |
defp cardinality_to_empty(:one), do: %{} | |
defp cardinality_to_empty(:many), do: [] | |
def encode(struct, opts) do | |
struct | |
|> Map.from_struct() | |
|> Enum.reduce(%{}, fn | |
{k, %Ecto.Association.NotLoaded{} = v}, acc -> | |
Map.put(acc, k, cardinality_to_empty(v.__cardinality__)) | |
{k, v}, acc -> | |
Map.put(acc, k, v) | |
end) | |
|> Map.drop([:__meta__, :__struct__] ++ unquote(drop_fields)) | |
|> Jason.Encode.map(opts) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment