Phoenix.Sync.Router (Phoenix.Sync v0.6.0)

View Source

Provides router macros to simplify the exposing of Electric shape streams within your Phoenix or Plug application.

Phoenix Integration

When using within a Phoenix application, you should just import the macros defined here in your Phoenix.Router module:

defmodule MyAppWeb.Router do
  use Phoenix.Router

  import Elixir.Phoenix.Sync.Router

  scope "/shapes" do
    sync "/all-todos", MyApp.Todos.Todo

    sync "/pending-todos", MyApp.Todos.Todo,
      where: "completed = false"
  end
end

Plug Integration

Within your Plug.Router module, use Elixir.Phoenix.Sync.Router and then add your sync routes:

defmodule MyApp.Plug.Router do
  use Plug.Router, copy_opts_to_assign: :options
  use Elixir.Phoenix.Sync.Router

  plug :match
  plug :dispatch

  sync "/shapes/all-todos", MyApp.Todos.Todo

  sync "/shapes/pending-todos", MyApp.Todos.Todo,
    where: "completed = false"
end

You must use the copy_opts_to_assign option in Plug.Router in order for the sync macro to get the configuration defined in your application.ex start/2 callback.

Transforms

You can add a transform function to your shapes as explained in Phoenix.Sync.shape/2 but, because sync/2 and sync/3 are macros, you need to use the {module, function, args} form when declaring the transform function.

  defmodule MyApp.Router do
    use Plug.Router, copy_opts_to_assign: :options

    # ...

    sync "/shapes/pending-todos", MyApp.Todos.Todo,
      where: "completed = false",
      transform: {MyApp.Router, :transform_todo, ["[PENDING]"]}

    def transform_todo(msg, prefix) do
      Map.update!(msg, "values", fn todo ->
        Map.put(todo, "title", prefix <> " " <> todo["title"])
      end)
    end
  end

Summary

Functions

Defines a synchronization route for streaming Electric shapes.

Create a synchronization route from an Ecto.Schema plus shape options.

Functions

sync(path, opts)

(macro)

Defines a synchronization route for streaming Electric shapes.

The shape can be defined in several ways:

Using Ecto Schemas

Defines a synchronization route for streaming Electric shapes using an Ecto schema.

sync "/all-todos", MyApp.Todo

Note: Only Ecto schema modules are supported as direct arguments. For Ecto queries, use the query option in the third argument or use Phoenix.Sync.Controller.sync_render/3.

Using Ecto Schema and where clause

sync "/incomplete-todos", MyApp.Todo, where: "completed = false"

Using an explicit table

sync "/incomplete-todos", table: "todos", where: "completed = false"

See the section on Shape definitions for more details on keyword-based shapes.

sync(path, queryable, opts)

(macro)

Create a synchronization route from an Ecto.Schema plus shape options.

sync "/my-shape", MyApp.Todos.Todo,
  where: "completed = false"

See sync/2.