Casting the incoming controller parameters
If available in Hex, the package can be installed
by adding construct_params
to your list of dependencies in mix.exs
:
def deps do
[
{:construct_params, "~> 0.3.0"}
]
end
Documentation can be found at https://hexdocs.pm/construct_params.
ConstractParams provides a macro for controller params casting.
- First, you need to create a module that cast the input parameters.
For casting uses construct library.
defmodule MyAppWeb.Api.Requests.Users.Index do
use Construct do
field(:next_page, :string, default: nil)
field(:limit, :integer, default: nil)
field(:user_id, :integer, default: nil)
end
end
- Then add a decorator to the action with the parameters you want to cast.
defmodule MyAppWeb.Api.UsersController do
use ConstructParams.CastDecorator
@decorate cast(MyAppWeb.Api.Requests.Users.Index)
def index(conn, params) do
end
end
In case of a successful casting, the controller action params are replaced with the casted data.
Otherwise the appropriate FallbackController
is called with {:error, errors}
parameters.