Torque.Encoder protocol (torque v0.4.0)

Copy Markdown View Source

Optional protocol for encoding Elixir structs as JSON.

Torque's NIF encoder rejects structs (maps carrying an atom __struct__ key) with {:error, :unhandled_struct}. When a struct implements this protocol, encode/1 runs it first and encodes the returned term instead, recursively.

The protocol is deliberately opt-in: a struct without an implementation is an error, never silently dropped fields.

Torque ships implementations for Date, Time, NaiveDateTime, and DateTime, each encoding as its ISO 8601 string.

Deriving

Structs can derive the implementation, encoding all fields or a subset via :only / :except:

@derive {Torque.Encoder, only: [:id, :name]}
defstruct [:id, :name, :secret]

@derive {Torque.Encoder, except: [:secret]}
defstruct [:id, :name, :secret]

Prefer :only to avoid accidentally leaking private information when new fields are added later.

Example

defimpl Torque.Encoder, for: Decimal do
  def encode(decimal), do: Decimal.to_string(decimal)
end

Torque.encode!(%{price: Decimal.new("37.50")})
#=> ~s({"price":"37.50"})

Implementation contract

encode/1 must return a term that can be encoded without expanding the same struct again. Returning the struct itself, or a term containing it, would expand forever; expansion is bounded at 128 levels and encoding fails with :encoder_expansion_too_deep beyond that bound.

Summary

Types

t()

All the types that implement this protocol.

Types

t()

@type t() :: term()

All the types that implement this protocol.

Functions

encode(term)

@spec encode(term()) :: term()