tanweerdev
Better Jason encoder for schemas automatically
I got this warning
warning: the Jason.Encoder protocol has already been consolidated, an implementation for Any has no effect. If you want to implement protocols after compilation or during tests, check the “Consolidation” section in the documentation for Kernel.defprotocol/2 lib/encoder.ex:1
warning: redefining module Jason.Encoder.Any (current version loaded from /Users/dev/projects/haitracker.com/haitracker-be/_build/dev/lib/jason/ebin/Elixir.Jason.Encoder.Any.beam) lib/encoder.ex:1
with the following encoder
defimpl Jason.Encoder, for: Any do
def encode(%{__struct__: _} = struct, _options) do
skip_keys =
case struct.__struct__ do
Haitracker.User ->
[
:local_password_hash,
:login_status_message
]
# TODO: define skip keys for each model and pass to this function
_whatever ->
[]
end
struct
|> Map.from_struct()
|> sanitize_map(skip_keys)
|> Jason.encode!()
end
defp sanitize_map(map, skip_keys) do
filter = fn {key, val} ->
cond do
key in [:__meta__, :__struct__] ->
false
is_map(val) ->
Ecto.assoc_loaded?(val)
key not in skip_keys ->
true
true ->
false
end
end
map
|> Enum.filter(filter)
|> Enum.into(%{})
end
end
I am wondering if there is a better way to encode all of the schemas I have using Jason with just single encoder config file so that all of the encoding options are defined at one place.
Marked As Solved
idi527
Then maybe return an object
{
name: "Association.NotLoaded",
__field__: "friends"
}
Also Liked
idi527
You can define an encoder for ecto’s Ecto.Association.NotLoaded then.
idi527
You can return "NotLoaded". Following your logic, skipping it would be incorrect as well (the field does exist).







