Tarams v0.2.0 Tarams View Source
Function for parsing and validating input params with predefined schema
Basic usage
@index_params_schema %{
keyword: :string,
status: [type: string, required: true],
group_id: [type: :integer, validate: {:number, [greater_than: 0]}]
}
def index(conn, params) do
with {:ok, better_params} <- Tarams.parse(@index_params_schema, params) do
# do anything with your params
else
{:error, changset} -> # return params error
end
end
A Schema is a simple map of field: options
Sample schema
schema1 = %{
keyword: :string
status: [type: :string, required: true, validate: {:inclusion, ["open", "processing", "completed"]}],
page: [type: :integer, default: 1],
start_date: [type: :date, default: &Timex.today/0]
}Field options
- If there is no options, a field can be written in short form
<field_name>: <type>. requiredis false by default, this field is used to check if a field is required or notvalidatedefine how a field is validated. You can use any validation whichEcto.Changesetsupports. There is a simple rule to map schema declaration withEcto.Changesetvalidation function. Simply concatenatevalidateand validation type to getEcto.Changesetvalidation function.
Example
%{status: [type: string, validate: {:inclusion, ["open", "pending"]}]}
# is translated to
Ecto.Changeset.validate_inclustion(changeset, :status, ["open", "pending"])default: set default value. It could be a value or a function, if is is a function, it will be evaluated each timeparsefunction is called.
Example
%{
category: [type: :string, default: "elixir"],
end_date: [type: :date, default: &Timex.today/1]
}cast_func: custom function to cast raw value to schema type. This iscast_funcspecfn(any) :: {:ok, any} | {:error, binary}By defaut,parsefunction usesEcto.Changesetcast function for built-in types, withcast_funcyou can define your own cast function for your custom type. Exampleschema = %{ status: [type: {:array, :string}, cast_func: fn value -> {:ok, String.split(",")} end] } Tarams.parse(schema, %{status: "processing,dropped"})
Link to this section Summary
Functions
cast fields with custom cast function
Parse and validate input params with predefined schema
Link to this section Functions
cast fields with custom cast function
Specs
parse(map(), map()) :: {:ok, map()} | {:error, Ecto.Changeset.t()}
Parse and validate input params with predefined schema