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>.
  • required is false by default, this field is used to check if a field is required or not
  • validate define how a field is validated. You can use any validation which Ecto.Changeset supports. There is a simple rule to map schema declaration with Ecto.Changeset validation function. Simply concatenate validate and validation type to get Ecto.Changeset validation 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 time parse function 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 is cast_func spec fn(any) :: {:ok, any} | {:error, binary} By defaut, parse function uses Ecto.Changeset cast function for built-in types, with cast_func you can define your own cast function for your custom type. Example
    schema =
    %{
      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

Link to this function

cast_custom_fields(changeset, custom_cast_fields, params)

View Source

cast fields with custom cast function

Specs

parse(map(), map()) :: {:ok, map()} | {:error, Ecto.Changeset.t()}

Parse and validate input params with predefined schema