jkbbwr

jkbbwr

Conditionally construct map

So I have found a pothole and I am not sure what the solution is.

I have a pretty standard JSON api in phoenix, I am using ecto, and I am mapping those to maps inside the ThingJSON this is all pretty standard.

Now depending on the route, the controller might decide it doesn’t want to preload some data. For example

%Aos.Schema.Shipyard{
  __meta__: #Ecto.Schema.Metadata<:loaded, "shipyard">,
  id: "103b0451-7396-4f11-9cf8-7081c1829f5e",
  port_id: "a748b9d2-40ff-4f14-8c8c-258b343145eb",
  port: %Aos.Schema.Port{
    __meta__: #Ecto.Schema.Metadata<:loaded, "port">,
    id: "a748b9d2-40ff-4f14-8c8c-258b343145eb",
    name: "London",
    shortcode: "lond",
    destinations: #Ecto.Association.NotLoaded<association :destinations is not loaded>,
    ships: #Ecto.Association.NotLoaded<association :ships is not loaded>,
    shipyard: #Ecto.Association.NotLoaded<association :shipyard is not loaded>,
    agents: #Ecto.Association.NotLoaded<association :agents is not loaded>,
    inserted_at: ~U[2024-07-01 02:02:57Z],
    updated_at: ~U[2024-07-01 02:02:57Z]
  },
  ships: [
    %Aos.Schema.ShipyardStock{
      __meta__: #Ecto.Schema.Metadata<:loaded, "shipyard_stock">,
      id: "8117b318-b0ef-4aa7-be31-88437acbe8fc",
      shipyard_id: "103b0451-7396-4f11-9cf8-7081c1829f5e",
      shipyard: #Ecto.Association.NotLoaded<association :shipyard is not loaded>,
      ship_id: "0a238468-1cf0-47b4-b891-d5936d6554a8",
      ship: #Ecto.Association.NotLoaded<association :ship is not loaded>,
      cost: 100,
      inserted_at: ~U[2024-07-01 02:02:57Z],
      updated_at: ~U[2024-07-01 02:02:57Z]
    }
  ],
  inserted_at: ~U[2024-07-01 02:02:57Z],
  updated_at: ~U[2024-07-01 02:02:57Z]
}

On one route it might want to preload the :ships but on another it might not want to.

I have some pretty standard view code that looks like this


  def render("shipyards.json", %{page: page}) do
    %{
      data: for(yard <- page.entries, do: shipyard(yard)),
      meta: %{
        page_number: page.page_number,
        page_size: page.page_size,
        total_entries: page.total_entries,
        total_pages: page.total_pages
      }
    }
  end

  def shipyard(shipyard) do
    %{
      id: shipyard.id,
      port: PortJSON.port(shipyard.port)
    }
  end

Now I want to modify the shipyard function to also display the ships but only if the assoc is actually preloaded.

Okay so I think

  def shipyard(shipyard) do
    %{
      id: shipyard.id,
      port: PortJSON.port(shipyard.port),
      ships:
        if Ecto.assoc_loaded?(shipyard.ships) do
          for(entry <- shipyard.ships, do: stock(entry))
        else
          # ???
        end
    }
  end

Problem is, if ships is not loaded it will export json of ships: null which is misleading IMO. I’d rather it just omitted the key.

I could do something like this

  def render_if(map, key, assoc, render) do
    if Ecto.assoc_loaded?(assoc) do
      Map.put(map, key, render.(assoc))
    else
      map
    end
  end

  def shipyard(shipyard) do
    %{
      id: shipyard.id,
      port: PortJSON.port(shipyard.port)
    }
    |> render_if(:ships, shipyard.ships, &stock/1)
  end

But it feels kinda wrong.

Also why is Ecto.assoc_loaded? not available as a guard.

Anyone got any ideas?

Most Liked

tfwright

tfwright

I don’t think there’s anything wrong with the way you’re handling it. I have done similar although I had a util that constructed the json with variable guards, among them filtering out unloaded associations–something like this:

def serialize(data) do
  Map.flat_map(data, fn 
    {field, %Ecto.AssocNotLoaded{}} -> []
    {field, assoc = %{}} -> [{field, serialize(assoc)}]
    {field, val} -> [{field, val}]
  end)
  # other selecting/filtering...
end
dimitarvp

dimitarvp

You can pattern match on Ecto.AssocNotLoaded and then have the map construction not include the key in that clause, or you can put nil and then have Enum.reject that deletes any map pairs with a nil value. Either one would be just fine.

Last Post!

gregvaughn

gregvaughn

I’d likely use a filter or guard is_list(shipyard.ships)

Where Next?

Popular in Questions Top

jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
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
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
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
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New

We're in Beta

About us Mission Statement