-
Notifications
You must be signed in to change notification settings - Fork 529
Scalar Recipes
Randy Thompson edited this page Jun 1, 2018
·
20 revisions
UUID (using UUID)
defmodule MyApp.Schema.Types.Custom.UUID do
@moduledoc """
The UUID scalar type allows UUID4 compliant strings to be passed in and out.
Requires `{ :uuid, "~> 1.1" }` package: https://github.com/zyro/elixir-uuid
"""
use Absinthe.Schema.Notation
scalar :uuid, name: "UUID" do
description("""
The `UUID` scalar type represents UUID4 compliant string data, represented as UTF-8
character sequences. The UUID type is most often used to represent unique
human-readable ID strings.
""")
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 UUID.info(value) do
{:ok, result} ->
if Keyword.get(result, :version) == 4 do
{:ok, Keyword.get(result, :uuid)}
else
:error
end
_ ->
:error
end
end
defp decode(%Absinthe.Blueprint.Input.Null{}) do
{:ok, nil}
end
defp decode(_) do
:error
end
defp encode(value), do: value
end
UUID (using Ecto.UUID)
@desc """
The UUID scalar type represents a version 4 (random) UUID. Any binary not conforming to this format will be flagged.
"""
defmodule MyApp.Schema.Types.Custom.UUID do
use Absinthe.Schema.Notation
alias Ecto.UUID
scalar :uuid, name: "UUID" do
serialize &UUID.cast!/1
parse &cast_uuid/1
end
defp cast_uuid(%Absinthe.Blueprint.Input.String{value: value}) do
UUID.cast(value)
end
defp cast_uuid(%Absinthe.Blueprint.Input.Null{}) do
{:ok, nil}
end
defp cast_uuid(_) do
:error
end
end
JSON (using Jason)
defmodule MyApp.Schema.Types.Custom.JSON do
@moduledoc """
The Json scalar type allows arbitrary JSON values to be passed in and out.
"""
use Absinthe.Schema.Notation
scalar :json, 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