Skip to content

Instantly share code, notes, and snippets.

@nuxlli
Created December 3, 2019 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nuxlli/baa4dd95dce8b8f1960f7245466860b1 to your computer and use it in GitHub Desktop.
Save nuxlli/baa4dd95dce8b8f1960f7245466860b1 to your computer and use it in GitHub Desktop.
defmodule Web.Graphql.Types.Scalars.JSON do
@moduledoc """
The Json scalar type allows arbitrary JSON values to be passed in and out.
Requires `{ :jason, "~> 1.1" }` package: https://github.com/michalmuskala/jason
"""
use Absinthe.Schema.Notation
scalar :json_text, name: "Json" do
description("""
The `Json` scalar type represents arbitrary json string data, represented as UTF-8
character sequences. The Json type is most often used to represent a free-form
human-readable json string.
""")
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
case Jason.decode(value) do
{:ok, result} -> {:ok, result}
_ -> :error
end
end
defp decode(%Absinthe.Blueprint.Input.Null{}) do
{:ok, nil}
end
defp decode(_) do
:error
end
defp encode(value), do: value
end
defmodule Web.Graphql.Types.Scalars do
@moduledoc false
use IziAPIWeb.Graphql, :graphql
require Logger
@desc """
The `DateTime` scalar type represents full date and time in UTC.
(e.g. "2017-06-19T22:06:37.205849Z").
https://github.com/bitwalker/timex/blob/master/lib/format/datetime/formatters/default.ex
"""
scalar :date_time, description: "ISOz time" do
parse(fn input ->
case Timex.parse(input.value, "{ISO:Extended:Z}") do
{:error, _reason} -> :error
result -> result
end
end)
serialize(&Timex.format!(&1, "{ISO:Extended:Z}"))
end
scalar :short_time, description: "Time in HH:MM format" do
parse(fn input ->
case Timex.parse(input.value, "{h24}:{m}") do
{:error, _reason} -> :error
result -> result
end
end)
serialize(&Timex.format!(&1, "{h24}:{m}"))
end
@desc """
The `Date` scalar type represents a ISO date.
(e.g. "2017-06-19").
"""
scalar :date, description: "ISO date" do
parse(fn input ->
case Timex.parse(input.value, "{ISOdate}") do
{:error, _reason} -> :error
result -> result
end
end)
serialize(&Timex.format!(&1, "{ISOdate}"))
end
end
defmodule Web.Graphql.Schema do
import_types(Web.Graphql.Types.Scalars)
import_types(Web.Graphql.Types.Scalars.JSON)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment