Hey, guys.
Recently, I created a new package called cozy_params
for casting and validating params.
It is based on Ecto, and has Ecto-like API.
An example integrating with Phoenix:
defmodule DemoWeb.PageController do
use DemoWeb, :controller
import CozyParams
action_fallback DemoWeb.FallbackController
defparams :product_search do
field :name, :string, required: true
embeds_many :tags do
field :name, :string, required: true
end
end
def index(conn, params) do
with {:ok, data} <- product_search(params) do
# ...
end
end
end
defmodule DemoWeb.FallbackController do
use DemoWeb, :controller
# ...
# handle errors for cozy_params
def call(conn, {:error, params_changeset: %Ecto.Changeset{} = changeset}) do
messages = CozyParams.get_error_messages(changeset)
# render messages in HTML, JSON, etc.
end
# handle errors for normal changsets from Ecto.
def call(conn, {:error, %Ecto.Changeset{} = changeset}) do
# ...
end
# ...
end
You can find more details in:
- GitHub page - GitHub - cozy-elixir/cozy_params: Provides Ecto-like API for casting and validating params..
- HexDoc: CozyParams — cozy_params v2.1.0
Hope you guys like it.
A development story:
A week ago, I planned to write this package. But, I only know a little about Elixir’s AST and macros. Then, I found a book - Metaprogramming Elixir, and read it last weekend.
The book helps me a lot. And now, I’m an AST newbie in Elixir world. Yeah!