chore: more fluent datetime type casting

This commit is contained in:
Zach Daniel 2023-03-03 11:59:15 -05:00
parent ccdbafa730
commit a45267441a
2 changed files with 24 additions and 0 deletions

View file

@ -6,6 +6,8 @@ defmodule Ash.Type.UtcDatetime do
""" """
use Ash.Type use Ash.Type
@beginning_of_day Time.new!(0, 0, 0)
@impl true @impl true
def storage_type, do: :utc_datetime def storage_type, do: :utc_datetime
@ -17,6 +19,16 @@ defmodule Ash.Type.UtcDatetime do
end end
@impl true @impl true
def cast_input(%Date{} = date, constraints) do
case DateTime.new(date, @beginning_of_day) do
{:ok, value} ->
cast_input(value, constraints)
_ ->
{:error, "Date could not be converted to datetime"}
end
end
def cast_input(value, _) do def cast_input(value, _) do
Ecto.Type.cast(:utc_datetime, value) Ecto.Type.cast(:utc_datetime, value)
end end

View file

@ -6,6 +6,8 @@ defmodule Ash.Type.UtcDatetimeUsec do
""" """
use Ash.Type use Ash.Type
@beginning_of_day Time.new!(0, 0, 0)
@impl true @impl true
def storage_type, do: :utc_datetime_usec def storage_type, do: :utc_datetime_usec
@ -17,6 +19,16 @@ defmodule Ash.Type.UtcDatetimeUsec do
end end
@impl true @impl true
def cast_input(%Date{} = date, constraints) do
case DateTime.new(date, @beginning_of_day) do
{:ok, value} ->
cast_input(value, constraints)
_ ->
{:error, "Date could not be converted to datetime"}
end
end
def cast_input(value, _) do def cast_input(value, _) do
Ecto.Type.cast(:utc_datetime_usec, value) Ecto.Type.cast(:utc_datetime_usec, value)
end end