tanweerdev

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

idi527

Then maybe return an object

{
  name: "Association.NotLoaded",
  __field__: "friends"
}

Also Liked

idi527

idi527

You can define an encoder for ecto’s Ecto.Association.NotLoaded then.

idi527

idi527

You can return "NotLoaded". Following your logic, skipping it would be incorrect as well (the field does exist).

Where Next?

Popular in Questions Top

tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

We're in Beta

About us Mission Statement