# `Electric.Client.ValueMapper`
[🔗](https://github.com/electric-sql/electric/tree/%40core/elixir-client%400.9.4/packages/elixir-client/lib/electric/client/value_mapper.ex#L1)

A behaviour for mapping the `value` fields of [`Message.ChangeMessage`](`Electric.Client.Message.ChangeMessage`) messages
from the shape stream.

This requires implementing a single function `c:for_schema/2`.

Electric sends schema information with every response. For example the schema
of the `foo` table from the [Electric
Quickstart](https://electric-sql.com/docs/quickstart) is

    %{
      id: %{type: "int4", pk_index: 0, not_null: true},
      name: %{type: "varchar", max_length: 255},
      value: %{type: "float8"}
    }

The `c:for_schema/2` function receives this schema as the first argument and it
must return a 1-arity function that will map the value structs received from
Electric to the desired format.

E.g

    # the schema for the `foo` table
    schema = %{
      id: %{type: "int4", pk_index: 0, not_null: true},
      name: %{type: "varchar", max_length: 255},
      value: %{type: "float8"}
    }

    # get the mapper function for this schema
    mapper_fun = Electric.Client.ValueMapper.for_schema(schema, opts = [])

    value = %{
      "id" => "1",
      "name" => "James",
      "value" => "45.6"
    }

    # the mapping parses the integer and float values to their respective
    # Elixir/Erlang types.
    mapper_fun.(value)
    %{
      "id" => 1,
      "name" => "James",
      "value" => 45.6
    }

The current implementation only handles integer and float values. Every other
column is left as a binary.

# `mapper_fun`

```elixir
@type mapper_fun() :: (Electric.Client.Message.ChangeMessage.value() -&gt; term())
```

# `opts`

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

# `for_schema`

```elixir
@callback for_schema(Electric.Client.schema(), opts()) :: mapper_fun()
```

Given the schema information passed from the electric server should return a
1-arity function that takes a values map, which is a map of column names to
string values, and returns a version with the values cast to some appropriate
Elixir type.

---

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