Magik.Params (Magik v0.10.0) View Source

Params provide some helpers method to work with parameters

Link to this section Summary

Functions

Cast and validate params with given schema. See Magik.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

Specs

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

Cast and validate params with given schema. See Magik.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} <- Magik.Params.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

Specs

clean_nil(any()) :: any()

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

Example

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

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

plug_srub(conn, keys \\ [])

View Source

A plug which do srubbing params

Use in Router

defmodule MyApp.Router do
  ...
  plug Magik.Params.plug_srub
  ...
end

Use in controller

plug Magik.Params.plug_srub when action in [:index, :show]
# or specify which field to scrub
plug Magik.Params.plug_srub, ["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"}
Magik.Params.scrub_param(params)
# => %{"keyword" => nil, "email" => nil, "type" => "customer"}

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