View Source Electric.Client.ValueMapper behaviour (Electric Client v0.2.0)

A behaviour for mapping the value fields of Message.ChangeMessage messages from the shape stream.

This requires implementing a single function for_schema/2.

Electric sends schema information with every response. For example the schema of the foo table from the Electric Quickstart is

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

The 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.

Summary

Callbacks

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.

Types

Callbacks

Link to this callback

for_schema(schema, opts)

View Source
@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.