Bolty.ResponseEncoder.Json protocol (Bolty v0.0.12)

Copy Markdown

Protocol controlling how a value is made jsonable.

Its only purpose is to convert Bolt Bolty specific structures into elixir buit-in types which can be encoed in json by Jason.

Deriving

If the provided default implementation don't fit your need, you can override with your own implementation.

Example

Let's assume that you don't want Node's id available as they are Neo4j's ones and are not reliable because of id reuse and you want to have you own uuid in place. Instead of:

  {
    id: 0,
    labels: ["TestNode"],
    properties: {
      uuid: "837806a7-6c37-4630-9f6c-9aa7ad0129ed"
      value: "my node"
    }
  }

you want:

  {
    uuid: "837806a7-6c37-4630-9f6c-9aa7ad0129ed",
    labels: ["TestNode"],
    properties: {
      value: "my node"
    }
  }

You can achieve that with the following implementation:

defimpl Bolty.ResponseEncoder.Json, for: Bolty.Types.Node do
  def encode(node) do
    new_props = Map.drop(node.properties, :uuid)

    node
    |> Map.from_struct()
    |> Map.put(:uuid, node.properties.uuid)
    |> Map.put(:properties, new_props)
  end
end

It is also possible to provide implementation that returns structs or updated Bolty.Types, the use of a final Bolty.ResponseEncoder.Json.encode() will ensure that these values will be converted to jsonable ones.

Summary

Types

t()

All the types that implement this protocol.

Functions

Convert a value in a jsonable format

Types

t()

@type t() :: term()

All the types that implement this protocol.

Functions

encode(value)

@spec encode(any()) :: any()

Convert a value in a jsonable format