Kurama
Kurama

Reputation: 629

How to specify a format of a parameter in URL in Elixir Phoenix framework?

How can I specify the format of a certain parameters in a URL? For example, for this URL: my_website.com/users/123 I want the user_id parameter in the URL to be integer and positive.

How can I do that? Is it done via web/routes.ex via regular expressions?

Upvotes: 4

Views: 2668

Answers (2)

Dogbert
Dogbert

Reputation: 222128

This is not possible in the Router in Phoenix because of the way the Router is implemented -- it can only match a path segment (text between /) with an exact constant string, a string with a constant prefix, or any string. You can check it manually in the controller action like this:

def show(conn, %{"user_id" => user_id}) do
  case Integer.parse(user_id) do
    {user_id, ""} when user_id > 0 ->
      # user_id is valid positive integer
      text(conn, "ok")
    _ ->
      # user_id was either not an integer or a negative integer
      text(conn, "not ok")
  end
end

Upvotes: 5

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

This is usually being done with Plugs. According to the documentation:

Module plugs are another type of Plug that let us define a connection transformation in a module. The module only needs to implement two functions:

  • init/1 which initializes any arguments or options to be passed to call/2
  • call/2 which carries out the connection transformation. call/2 is just a function plug that we saw earlier
defmodule HelloPhoenix.Plugs.Checker do
  import Plug.Conn

  @validator ~r|\A\d+\z|

  def init(default), do: default

  def call(%Plug.Conn{params: %{"user_id" => user_id}} = conn, _default) do
    # ⇓ HERE
    unless Regex.match(@validator, user_id), do: raise
    assign(conn, :user_id, user_id)
  end
end

Upvotes: 3

Related Questions