# `LiveReact.Encoder`
[🔗](https://github.com/mrdotb/live_react/blob/v2.0.0/lib/live_react/encoder.ex#L1)

Protocol for encoding values to JSON for LiveReact.

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.

By default all keys except the `:__struct__` key are encoded.

## Example

    defmodule User do
      @derive LiveReact.Encoder
      defstruct [:name, :email, :password]
    end

If we called `@derive {LiveReact.Encoder, only: [:name, :email]}`, only the
specified fields would be encoded. If we called
`@derive {LiveReact.Encoder, except: [:password]}`, all fields except the
specified ones would be encoded.

## Deriving outside of the module

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

## Custom implementations

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

# `opts`

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

# `t`

```elixir
@type t() :: term()
```

# `encode`

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

Encodes a value to one of the primitive types.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
