RpcElixir.Types (elixir_ts_rpc v0.0.2)

Copy Markdown View Source

Type system for RPC procedure input and output specs.

Three entry points. resolve/1 normalizes a shorthand spec into the internal IR map. validate/2 checks untrusted input against a spec. serialize/2 prepares handler output for JSON encoding. See Supported types for the type-mapping tables.

Atom keys in validated input

A successful validate/2 returns object values with atom keys, e.g. %{id: "abc"}. Handlers therefore receive atom-keyed maps. Pattern-match accordingly:

def get(%{id: id}, _ctx), do: ...     # correct
def get(%{"id" => id}, _ctx), do: ... # wrong — key will be missing

Summary

Types

Internal IR map used across the type system. It always has a kind string key.

Functions

Converts a shorthand spec term to an internal_spec IR map. Accepts an atom, tagged tuple, or map.

Serializes a server-produced value against spec into a JSON-encodable shape.

Validates user-supplied value against spec. Returns {:ok, coerced} or {:error, tree}.

Types

internal_spec()

@type internal_spec() :: %{optional(atom()) => term(), kind: String.t()}

Internal IR map used across the type system. It always has a kind string key.

Functions

resolve(already_resolved)

@spec resolve(
  :string
  | :integer
  | :float
  | :boolean
  | {:optional, term()}
  | {:nullable, term()}
  | {:list, term()}
  | {:stream, term()}
  | internal_spec()
  | map()
) :: internal_spec()

Converts a shorthand spec term to an internal_spec IR map. Accepts an atom, tagged tuple, or map.

serialize(spec, value)

@spec serialize(term(), term()) :: term()

Serializes a server-produced value against spec into a JSON-encodable shape.

spec may be a shorthand spec term or an already-resolved IR map. See resolve/1. It assumes value already conforms, e.g. fresh from a handler. It raises on contract violations such as missing required fields. Those indicate programmer error, not bad input.

validate(spec, value)

@spec validate(term(), term()) :: {:ok, term()} | {:error, map()}

Validates user-supplied value against spec. Returns {:ok, coerced} or {:error, tree}.

spec may be a shorthand spec term or an already-resolved IR map. See resolve/1 for the shorthand forms. This is for untrusted input, such as decoded JSON. So contract violations come back as error trees, not raises. Object values in {:ok, coerced} always have atom keys. See the module doc.