View Source CozyParams (cozy_params v0.2.0)
Expose more user friendly API for underlying modules.
Link to this section Summary
Functions
Defines a function for casting and validating params.
Extract error messages from %Ecto.Changeset{}
.
Link to this section Functions
Defines a function for casting and validating params.
Essentially, this macro is just a shortcut for using
CozyParams.Schema
.
Inspired by vic/params.
examples
Examples
defmodule Demo do
import CozyParams
defparams :product_search do
field :name, :string, required: true
end
def search(params) do
with {:ok, data} <- product_search(params) do
# process data
end
end
end
Above defparams :product_search do: block
will:
- create a module
Demo.CozyParams.ProductSearch
automatically. - inject
product_search/1
andproduct_search/2
into current module. And, these two functions will callDemo.CozyParams.ProductSearch.from
internally.
For more details of the schema definations in do: block
, check out CozyParams.Schema
.
defparams
can be used in any module, not limited to Phoenix controllers.In order to demonstrate this point, above example is using an normal
Demo
module, instead of a Phoenix controller.For better integration with Phoenix controllers, check out
CozyParams.PhoenixController
.
error-handling
Error handling
When external params are invalid, {:error, params_changeset: %Ecto.Changeset{}}
will be returned, which allows developers to match this pattern for handling errors.
If the error messages is required, CozyParams.get_error_messages/1
would be helpful.
Extract error messages from %Ecto.Changeset{}
.