LiveViewReact.Encoder protocol (liveview_react v1.0.0)

Copy Markdown View Source

Protocol for encoding values to JSON for LiveViewReact.

This protocol is used to safely transform structs into plain maps before calculating JSON patches. It ensures that struct fields are explicitly exposed and prevents accidental exposure of sensitive data.

It's very similar to Jason.Encoder, but it's converting structs to maps instead of strings.

Deriving

The protocol allows leveraging Elixir's @derive feature to simplify protocol implementation in trivial cases. Accepted options are:

  • :only - encodes only values of specified keys.
  • :except - encodes all struct fields except specified keys.

Derivation must explicitly provide exactly one of these options. A bare @derive LiveViewReact.Encoder is rejected so adding a sensitive field to a struct cannot silently expose it to the browser.

Example

defmodule User do
  @derive {LiveViewReact.Encoder, only: [:name, :email]}
  defstruct [:name, :email, :password]
end

only: [:name, :email] exposes those fields. except: [:password] exposes every current and future field except :password, so :only is preferred for data-bearing structs.

Deriving outside of the module

Protocol.derive(LiveViewReact.Encoder, User, only: [...])

Custom implementations

defimpl LiveViewReact.Encoder, for: User do
  def encode(struct, opts) do
    struct
    |> Map.take([:first, :second])
    |> LiveViewReact.Encoder.encode(opts)
  end
end

Summary

Types

Options forwarded unchanged through recursive protocol implementations.

t()

A value being encoded for LiveViewReact transport.

Functions

Encodes a value to one of the primitive types.

Types

opts()

@type opts() :: Keyword.t()

Options forwarded unchanged through recursive protocol implementations.

t()

@type t() :: term()

A value being encoded for LiveViewReact transport.

Functions

encode(value, opts)

@spec encode(t(), opts()) :: any()

Encodes a value to one of the primitive types.