View Source Parameter.Enum (Parameter v0.8.1)

Enum type represents a group of constants that have a value with an associated key.

examples

Examples

defmodule MyApp.UserParam do
  use Parameter.Schema

  enum Status do
    value :user_online, key: "userOnline"
    value :user_offline, key: "userOffline"
  end

  param do
    field :first_name, :string, key: "firstName"
    field :status, MyApp.UserParam.Status
  end
end

The Status enum should automatically translate the userOnline and userOffline values when loading to the respective atom values.

Parameter.load(MyApp.UserParam, %{"firstName" => "John", "status" => "userOnline"})
{:ok, %{first_name: "John", status: :user_online}}

Parameter.dump(MyApp.UserParam, %{first_name: "John", status: :user_online})
{:ok, %{"firstName" => "John", "status" => "userOnline"}}

Enum also supports a shorter version if the key and value are already the same:

defmodule MyApp.UserParam do
  ...
  enum Status, values: [:user_online,  :user_offline]
  ...
end

Parameter.load(MyApp.UserParam, %{"firstName" => "John", "status" => "user_online"})
{:ok, %{first_name: "John", status: :user_online}}

Using numbers is also allowed in enums:

enum Status do
  value :active, key: 1
  value :pending_request, key: 2
end

Parameter.load(MyApp.UserParam, %{"status" => 1})
{:ok, %{status: :active}}

It's also possible to create enums in different modules by using the enum/1 macro:

defmodule MyApp.Status do
  import Parameter.Enum

  enum do
    value :user_online, key: "userOnline"
    value :user_offline, key: "userOffline"
  end
end

defmodule MyApp.UserParam do
  use Parameter.Schema
  alias MyApp.Status

  param do
    field :first_name, :string, key: "firstName"
    field :status, Status
  end
end

And the short version:

enum values: [:user_online,  :user_offline]