debianize-mobilizon/lib/graphql/schema/custom/timezone.ex
Thomas Citharel 845bb6ac90
feat(graphql): validate timezone id as a GraphQL Scalar
Related to #1299

Signed-off-by: Thomas Citharel <tcit@tcit.fr>
2023-06-05 09:12:31 +02:00

36 lines
992 B
Elixir

defmodule Mobilizon.GraphQL.Schema.Custom.Timezone do
@moduledoc """
The timezone scalar type allows timezone ID strings to be passed in and out.
"""
use Absinthe.Schema.Notation
import Mobilizon.Web.Gettext, only: [dgettext: 3]
scalar :timezone, name: "Timezone" do
description("""
The `Timezone` scalar type represents a timezone identifier,
as registered in the IANA Time Zone Database.
""")
serialize(&encode/1)
parse(&decode/1)
end
@spec decode(Absinthe.Blueprint.Input.String.t()) :: {:ok, term} | :error
@spec decode(Absinthe.Blueprint.Input.Null.t()) :: {:ok, nil}
defp decode(%Absinthe.Blueprint.Input.String{value: value}) do
if Tzdata.zone_exists?(value),
do: {:ok, value},
else: {:error, dgettext("errors", "Timezone ID %{timezone} is invalid", timezone: value)}
end
defp decode(%Absinthe.Blueprint.Input.Null{}) do
{:ok, nil}
end
defp decode(_) do
:error
end
defp encode(value), do: value
end