Last active
May 29, 2024 03:52
-
-
Save Wigny/3f1b32f729632d5a7417c3d3c31cfbcd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule MyApp.Type.Duration do | |
use Ecto.Type | |
alias Postgrex.Interval | |
defguardp is_duration(value) when is_struct(value, Duration) | |
defguardp is_interval(value) when is_struct(value, Interval) | |
@impl true | |
def type, do: :interval | |
@impl true | |
def cast(value) when is_interval(value), do: {:ok, from_interval(value)} | |
def cast(value) when is_duration(value), do: {:ok, value} | |
def cast(_value), do: :error | |
@impl true | |
def load(value) when is_interval(value), do: {:ok, from_interval(value)} | |
@impl true | |
def dump(value) when is_duration(value), do: {:ok, to_interval(value)} | |
def dump(_value), do: :error | |
defp from_interval(interval) do | |
Duration.new!(month: interval.months, day: interval.days, second: interval.secs, microsecond: {interval.microsecs, 6}) | |
end | |
defp to_interval(duration) do | |
milliseconds = to_timeout(duration) | |
%Interval{microsecs: milliseconds * 1_000} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment