View Source CozyParams.PhoenixController (cozy_params v0.2.0)

Providing macros for integrating with Phoenix controllers.

Inspired by elixir-maru/maru_params.

examples

Examples

Extend just a controller:

defmodule DemoWeb.PageController do
  use DemoWeb, :controller
  use CozyParams.PhoenixController

  params :index do
    field :name, :string, required: true
  end

  def index(conn, params) do
    # + when external params are valid, `params` will be converted as a map with atom keys.
    # + when external params are invalid, `{:error, params_changeset: %Ecto.Changeset{}}`
    #   will be returned.
  end
end

Extend all controllers:

defmodule DemoWeb do
  # ...
  def controller do
    quote do
      use Phoenix.Controller, namespace: DemoWeb
      # ...

      use CozyParams.PhoenixController
    end
  end
end

defmodule DemoWeb.PageController do
  use DemoWeb, :controller

  params :index do
    field :name, :string, required: true
  end

  def index(conn, params) do
    # + when external params are valid, `params` will be converted as a map with atom keys.
    # + when external params are invalid, `{:error, params_changeset: %Ecto.Changeset{}}`
    #   will be returned.
  end
end

For more details of the schema definations in do: block, check out CozyParams.Schema.

error-handling

Error handling

As mentioned above, when external params are invalid, {:error, params_changeset: %Ecto.Changeset{}} will be returned, which allows developers to match this pattern in the fallback controller, and convert the changeset as error messages by using CozyParams.get_error_messages/1.

For example:

defmodule DemoWeb.PageController do
  use DemoWeb, :controller

  action_fallback DemoWeb.FallbackController

  params :index do
    field :name, :string, required: true
  end

  def index(conn, params) do
    # ...
  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

Link to this section Summary

Functions

Defines params for a given action.

Link to this section Functions

Link to this macro

params(action, list)

View Source (since 0.1.0) (macro)

Defines params for a given action.