TypedGql.JSON behaviour (TypedGql v0.13.0)

Copy Markdown View Source

Behaviour for JSON encoding/decoding.

By default, uses Elixir's built-in JSON module (available since Elixir 1.18) when present, falling back to Jason. If neither is available, raises at runtime.

To override the auto-detected default:

config :typed_gql, :json_library, Jason

A custom implementation must export encode!/1 and decode/1 (see @callback definitions below).

Summary

Functions

Decodes a JSON string. Returns {:ok, term} or {:error, reason}.

Encodes a term to a JSON string. Raises on failure.

Returns the configured JSON library module.

Normalizes a decode error to an exception.

Callbacks

decode(t)

@callback decode(String.t()) :: {:ok, term()} | {:error, term()}

encode!(term)

@callback encode!(term()) :: String.t()

Functions

decode(string)

@spec decode(String.t()) :: {:ok, term()} | {:error, term()}

Decodes a JSON string. Returns {:ok, term} or {:error, reason}.

encode!(term)

@spec encode!(term()) :: String.t()

Encodes a term to a JSON string. Raises on failure.

library()

@spec library() :: module()

Returns the configured JSON library module.

normalize_error(reason)

@spec normalize_error(term()) :: Exception.t()

Normalizes a decode error to an exception.

The configured library decides the error shape: Jason returns an exception struct, Elixir's JSON a plain tuple, and a custom one anything at all.