View Source CozyParams (cozy_params v2.1.1)

Expose more user friendly API for underlying modules.

Summary

Functions

Defines a function for casting and validating params.

Extract error messages from %Ecto.Changeset{}.

Extract error messages from %Ecto.Changeset{} with a given function.

Functions

Link to this macro

defparams(name, list)

View Source (since 0.1.0) (macro)

Defines a function for casting and validating params.

Essentially, this macro is just a shortcut for using CozyParams.Schema.

Inspired by vic/params.

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:

  1. create a module Demo.CozyParams.ProductSearch automatically.
  2. inject product_search/1 into current module. And, this function will call Demo.CozyParams.ProductSearch.from/1 internally.

For more details of the schema definitions in do: block, check out CozyParams.Schema.

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.

Link to this function

get_error_messages(changeset)

View Source (since 0.1.0)

Extract error messages from %Ecto.Changeset{}.

Link to this function

get_error_messages(changeset, msg_func)

View Source (since 1.1.0)

Extract error messages from %Ecto.Changeset{} with a given function.

The msg_func will be passed to Ecto.Changeset.traverse_errors/2, read doc of Ecto.Changeset.traverse_errors/2 for more information.