Building a day_of_week data type in Ash

Hi, I’m struggling a bit on how to implement a data-type for day of week in Ash. With plain ecto you’d do something like field :dow, Ecto.Enum, values: [sunday: 0, monday: 1, ... ], which also allows you to use the atom in a query like so: where(MySchema, [m], m.dow == :sunday).

Does the Ash Framework have a built-in way to achieve the equivalent? This is how I resolved it so far:

defmodule MyApp.Types.DayOfWeek do
  use Ash.Type

  @configuration Ecto.ParameterizedType.init(Ecto.Enum, values: [monday: 1, tuesday: 2, wednessday: 3, thursday: 4, friday: 5, saturday: 6, sunday: 0])

  # Be sure to add a matching enum to your Graphql-Schema
  def graphql_type, do: :day_of_week

  @impl Ash.Type
  def storage_type(_), do: :integer

  @impl Ash.Type
  def cast_input(nil, _), do: {:ok, nil}
  def cast_input(value, _), do: Ecto.Type.cast(__configuration__(), value)

  @impl Ash.Type
  def cast_stored(nil, _), do: {:ok, nil}
  def cast_stored(value, _), do: Ecto.Type.load(__configuration__(), value)

  @impl Ash.Type
  def dump_to_native(nil, _), do: {:ok, nil}
  def dump_to_native(value, _), do: Ecto.Type.dump(__configuration__(), value)

  def __configuration__, do: @configuration
end

The Enum Type should work pretty well for this. Ash.Type.Enum — ash v2.17.6 the doc has an example in it.

you just also need to add the graphql_type callback if you want to expose it over AshGraphql

1 Like