How to add Map in phoenix conn's params in Plug

The idea is not to subvert the intent behind Plug.Conn.params - it’s not a general data “dumping ground” - that is Plug.Conn.assigns job. So the strategy would be to put the information in Plug.Conn.assigns first and then combine it in the last possible moment. So start with

          {:ok, climes} ->
             conn =
               conn
               |> assign(:all_req,  %{"last_ip", "#{climes["ip"]}"})
               |> assign(:user_ip_checked, params)

And then have a helper function that assembles everything

def make_all_req(conn, params) do
  conn.assigns
  |> Map.get(:all_req, %{})
  |> Map.merge(conn.params)
  |> Map.merge(params)
end

which you can use at the last possible moment, like:

def get_posts_category(conn, %{"seo_alias_link" => _seo_alias_link, "page_number" => _page_number, "page_size" => _page_size, "token" => _token, "ptoken" => _ptoken} = params) do
   all_req = make_all_req(conn, params)
   ...
end

You really shouldn’t be sending the entire contents of the Plug.Conn structure.

  • The actual content may change in the next version of Plug.Conn
  • The organization of the Plug.Conn structure could change in the next version
  • By using Plug.Conn verbatim you are unnecessarily coupling other parts of your system to it (and the version that you started using).

In the interest of decoupling:

  • Decide what minimal information is actually useful.
  • Structure that information in a way the makes sense to your system. Your information structure has different reasons to change than those that will force a change on Plug.Conn.
2 Likes