Redis.Codec behaviour (Redis v0.8.0)

Copy Markdown View Source

Behaviour for custom value encoding/decoding.

A codec transforms values before they are sent to Redis and after they are received. This lets you transparently store structured data (JSON, Erlang terms, etc.) while keeping the Redis commands unchanged.

Built-in codecs

Usage

Codecs are not wired into the connection automatically. Instead, use the helper functions encode_value/2 and decode_result/2 to transform values at the call site:

codec = Redis.Codec.JSON

{:ok, encoded} = Redis.Codec.encode_value(codec, %{name: "Alice"})
{:ok, "OK"} = Redis.command(conn, ["SET", "user:1", encoded])

{:ok, raw} = Redis.command(conn, ["GET", "user:1"])
{:ok, %{"name" => "Alice"}} = Redis.Codec.decode_result(codec, raw)

Implementing a custom codec

defmodule MyApp.MsgpackCodec do
  @behaviour Redis.Codec

  @impl true
  def encode(term), do: {:ok, Msgpax.pack!(term, iodata: false)}

  @impl true
  def decode(binary), do: {:ok, Msgpax.unpack!(binary)}

  @impl true
  def content_type, do: "application/msgpack"
end

Summary

Callbacks

Returns the MIME content type for this codec (e.g. "application/json").

Decode a binary retrieved from Redis back into a term.

Encode a term into a binary suitable for storage in Redis.

Functions

Decode a result using the given codec module.

Decode a list of results using the given codec module.

Encode a value using the given codec module.

Callbacks

content_type()

@callback content_type() :: String.t()

Returns the MIME content type for this codec (e.g. "application/json").

decode(binary)

@callback decode(binary()) :: {:ok, term()} | {:error, term()}

Decode a binary retrieved from Redis back into a term.

encode(term)

@callback encode(term()) :: {:ok, binary()} | {:error, term()}

Encode a term into a binary suitable for storage in Redis.

Functions

decode_result(codec, value)

@spec decode_result(module(), term()) :: {:ok, term()} | {:error, term()}

Decode a result using the given codec module.

Passes nil through unchanged (for missing keys). Non-binary values are returned as-is, since they cannot be decoded.

decode_results(codec, results)

@spec decode_results(module(), [term()]) :: {:ok, [term()]} | {:error, term()}

Decode a list of results using the given codec module.

Useful for decoding pipeline or MGET results.

encode_value(codec, value)

@spec encode_value(module(), term()) :: {:ok, binary()} | {:error, term()}

Encode a value using the given codec module.

Returns {:ok, binary} on success or {:error, reason} on failure.