View Source Tarams (Tarams v1.4.0)

Params provide some helpers method to work with parameters

Link to this section Summary

Functions

Cast and validate params with given schema. See Tarams.Schema for instruction on how to define a schema And then use it like this

Clean all nil field from params, support nested map and list.

A plug which do srubbing params

Convert all parameter which value is empty string or string with all whitespace to nil. It works with nested map and list too.

Link to this section Functions

@spec cast(data :: map(), schema :: map()) :: {:ok, map()} | {:error, errors :: map()}

Cast and validate params with given schema. See Tarams.Schema for instruction on how to define a schema And then use it like this

def index(conn, params) do
  index_schema = %{
    status: [type: :string, required: true],
    type: [type: :string, in: ["type1", "type2", "type3"]],
    keyword: [type: :string, length: [min: 3, max: 100]],
  }

  with {:ok, data} <- Tarams.cast(params, index_schema) do
    # do query data
  else
    {:error, errors} -> IO.puts(errors)
  end
end
Link to this function

cast_array(type, value, acc \\ [])

View Source
@spec clean_nil(any()) :: any()

Clean all nil field from params, support nested map and list.

Example

params = %{"keyword" => nil, "email" => nil, "type" => "customer"}
Tarams.clean_nil(params)
# => %{"type" => "customer"}

params = %{user_ids: [1, 2, nil]}
Tarams.clean_nil(params)
# => %{user_ids: [1, 2]}
Link to this function

plug_scrub(conn, keys \\ [])

View Source

A plug which do srubbing params

Use in Router

defmodule MyApp.Router do
  ...
  plug Tarams.plug_scrub
  ...
end

Use in controller

plug Tarams.plug_scrub when action in [:index, :show]
# or specify which field to scrub
plug Tarams.plug_scrub, ["id", "keyword"] when action in [:index, :show]

Convert all parameter which value is empty string or string with all whitespace to nil. It works with nested map and list too.

Example

params = %{"keyword" => "   ", "email" => "", "type" => "customer"}
Tarams.scrub_param(params)
# => %{"keyword" => nil, "email" => nil, "type" => "customer"}

params = %{user_ids: [1, 2, "", "  "]}
Tarams.scrub_param(params)
# => %{user_ids: [1, 2, nil, nil]}