Elixir - Absinthe
01 Feb 2019tips
JSON scalar type
- https://hexdocs.pm/absinthe/custom-scalars.html
- https://github.com/absinthe-graphql/absinthe/wiki/Scalar-Recipes#json-using-jason
- https://elixirforum.com/t/absinthe-and-storing-jsonb/6741/2
- https://github.com/absinthe-graphql/absinthe/blob/master/lib/absinthe/type/custom.ex
# lib/my_app_web/schema/custom_types.ex
defmodule MyAppWeb.Schema.CustomTypes do
use Absinthe.Schema.Notation
alias Absinthe.Blueprint.Input.{Null, String}
scalar :json, name: "Json" do
parse(&decode/1)
serialize(&encode/1)
end
defp decode(%String{value: value}) do
case Jason.decode(value) do
{:ok, result} -> {:ok, result}
_ -> :error
end
end
defp decode(%Null{}), do: {:ok, nil}
defp decode(_), do: :error
# don't encode with Jason.encode!/2
defp encode(value), do: value
end