Standardize and validate data in Phoenix with the Tarams library

Tram Ho

The requirement to standardize and validate parameters passed from the client is a basic requirement when building Web APIs. I have a tutorial on using Ecto.Changeset to standardize in this article:

Parse and validate request param in Phoenix with Ecto

In this article, I will guide a short and simpler way using the Tarams library available. This library is actually Ecto.Changeset but it helps us not to have to repeat too much code like when using Ecto.Changeset

Some interesting features of Tarams:

  • Provides a simple way to define parameter structures
  • Allows defining dynamic default values
  • Allows defining functions to cast values ​​to the correct data type
  • Defines the function to validate the data

Here’s how to use Tarams . As an example we are writing an API to update employee profiles. The request is

1. The definition of the structure of the passed parameter is quite simple

Schema is simply a map where the key is the field name and value is a list option of that field.

2. Now add the constraints

  • To mark a field as required, add the option required: true
  • Taram also allows validate data to reuse Changeset ‘s validate functions

3. Now set the default values

default can be a value or a function. Every time the parameter parse, this function will be called to get its default value

4. Cast the parameter values ​​to the correct type

Many of the passed parameter values ​​must be converted to correct complex data types such as dates and lists. For example, if the date is passed as string 01/12/1994 , it must be converted to date type to reuse. Tarams supports defining a custom function to cast the value, which returns

  • {:ok, value} if parsing is successful
  • {:error, error_message} failure

5. Now use any

The parse function will parse and validate the data. If everything is fine, {:ok, data} will be returned and {:error, changeset} will be returned.

Done! Your code will become much simpler and more concise

Share the news now

Source : Viblo