Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match Phoenix request path with Route defined in database

When we send a request we have current path info in the conn struct. Let's say for patch request.

["v1", "users", "2"] or "v1/users/2"

I am writing a plug for users authorisation based on the path info in the db. In the db the paths are stored like this:

"v1/users/:id"

This is the path we get from running mix phx.routes. Is it possible that I can get the "v1/users/:id" instead of "v1/users/2" for the current path? so I can match it with the path stored in the db.

Is there any work around?

like image 290
script Avatar asked Dec 05 '18 05:12

script


1 Answers

A very hackey way to do it would be to manually replace the value in the path for the associated key.

In the conn struct, we have path_info: ["v1", "users", "2"] and path_params: %{"id" => "2"}, so we can do:

Enum.reduce(conn.path_params, conn.path_info, fn {key, value}, acc ->
  index = Enum.find_index(acc, fn x -> x == value end)
  List.replace_at(acc, index, ":#{key}")
end)
|> Enum.join("/")

And the output would be v1/users/:id.

Please be aware that this would fail if you have a parameter value that is the same as part of the route (which seems unlikely to happen). Also, if you have multiple parameters that can take the same value we would then be relying on the order of the parameters in path_params.

like image 99
Gabriel Prá Avatar answered Oct 21 '22 05:10

Gabriel Prá