Tarams, simplest library to parse and validate params

Hi, I have just published a new package named tarams. It provide a simple way to define schema, parse and validate your request parameters.

Here is how to use Tarams

@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
        IO.inspect(better_params.keyword}
        IO.inspect(better_params.status}
        IO.inspect(better_params.group_id}
        # do anything with your params
    else
        {:error, changset} -> # return params error
    end
end

Your feedback are welcome!

8 Likes

So this is just wrapping Ecto changesets?

This looks quite similar to what nimble_options does.

1 Like

Yes. It reduces the amount of code that I have to write for each param schema

It is quite similar, but Tarams wraps around Ecto.Changeset so you can use all validator that Ecto.Changeset supports.

In version 0.2.0, I added cast_func option which allow to define custom casting function for custom type.
In the previous version, tarams only supports built-in types and uses Ecto.Changeset.cast function to cast params value.

def my_array_parser(value) do
    if is_binary(value) do
        ids = 
            String.split(value, ",")
            |> Enum.map(&String.to_integer(&1))
        
        {:ok, ids}
    else
        {:error, "Invalid string"}
    end
end

schema = %{
    user_id: [type: {:array, :integer}, cast_func: &my_array_parser/1]
}

Tarams.parse(schema, %{user_id: "1,2,3"})