Is there a way to extract certain structure from a map?

Hi there,

I am currently trying to call an outside API from my elixir/phoenix API using HTTPoison for some POST and GET requests. I am stuck for File uploads.

I will receive as parameters to my API the parameters to send to the outside API and I need to extract the Plug.Upload structure to convert it to a FormData.File structure so that I can use it for httpoison-form-data

Example of an input MAP:

%{
     "one" => "test",
     "two" => "3",
      "myFile" => %Plug.Upload{
           content_type: "application/vnd.ms-excel",
           filename: "TEST.xls",
           path: "/tmp/some_path/multipart-123456789"
      }
}

The problem is I will not necessary know to which key of the map the structure will be associated, is there a way I can check by its type to convert it maybe ?

Thanks in advance for your help.

You can iterate it and find the first matching struct.

For example:

map |> Map.to_list() |> Enum.find(fn
  {_, %Plug.Upload{}} -> true
  _ -> false
end)
1 Like

Thanks a lot, I haven’t thought by just matching the type, using Enum.map and matching the value to Plug.Upload I solved my problem :slight_smile:

If you don’t care about the key you can also do:

map
|> Map.values
|> Enum.find(&match?(%Plug.Upload{}, &1))

This will return just the upload instead of a tuple of the upload and the key.

1 Like