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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With