Skip to content

Instantly share code, notes, and snippets.

@heyitsjames
Created October 12, 2021 20:09
Show Gist options
  • Save heyitsjames/3bf9739d18a4bb95989b864a118f510a to your computer and use it in GitHub Desktop.
Save heyitsjames/3bf9739d18a4bb95989b864a118f510a to your computer and use it in GitHub Desktop.
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