Mr_Coffeey

Mr_Coffeey

Any alternatives for @derive and Poison.Encoder?

Hi guys!

In this moment I am working in a large umbrella application composed for around 4 applications each one has their own models that are using this implementation for Poison.Encoder

defimpl Poison.Encoder, for: Any do
    def encode(%{__struct__: App.Models.Task} = struct, options) do
    struct =
        if struct.geom do
            {lon, lat} =  struct.geom.coordinates
            %{struct | lon: lon, lat: lat}
        else
            struct
        end
        encode_model(struct, options)
    end

    def encode(%{__struct__: _} = struct, options) do
        encode_model(struct, options)
    end

    def encode({lon, lat}, options) when is_float(lon) and is_float(lat) do
        %{lon: lon, lat: lat}
        |> sanitize_map()
        |> Poison.Encoder.Map.encode(options)
    end

    defp encode_model(model, options) do
        model
        |> Map.from_struct()
        |> sanitize_map()
        |> Poison.Encoder.Map.encode(options)
    end

    defp sanitize_map(map) do
        map
        |> Enum.filter(
            fn({_, %Ecto.Association.NotLoaded{}}) -> false
            ({:__meta__, _}) -> false
            ({:__struct__, _}) -> false
            ({_, _}) -> true
           end)
    |> Map.new()
    end
end

My model looks like:

# App.Models.Task
@derive {Poison.Encoder, only: [
  :address,
  :address_extra,
  :geom,
  :country,
  :dep_state,
  :city,
  :zip_code,
  :lat,
  :lon
]}
schema "tasks" do
  field(:address, :string)
  field(:address_extra, :string)
  field(:geom, Geo.Geometry)
  field(:country, :string)
  field(:dep_state, :string)
  field(:city, :string)
  field(:zip_code, :string)
  field(:lat, :float, virtual: true)
  field(:lon, :float, virtual: true)
  
  belongs_to(:service, App.Models.Service)
  timestamps()
end

This obviously doesn’t work once I want to compile my releases (using distillery) since I’m overriding the existing encoder implementations. So, in order to fix the issue I will need to implement Poison.Encoder using @derive in my models.

So the thing is, I know preloading the relationships is the way to go, but, what if I don’t want to preload all the relationships of my models? There are another way to go? If this is the only way, at least can I skip preloading relationships?

Thank you so much in advance for your time.

Marked As Solved

michalmuskala

michalmuskala

In general the protocol implementation is a bad idea for encoding domain entities like ecto structs - it’s very likely you’d like to differ how you encode them in different situations and protocols are global.

The way to go is to use phoenix views to translate from structs to simple data that can be encoded - take a look at the default code phoenix generates when you use phx.gen.json.

Where Next?

Popular in Questions Top

Tee
can someone please explain to me how Enum.reduce works with maps
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

We're in Beta

About us Mission Statement