View Source Electric.Phoenix.Gateway.Plug (Electric Phoenix v0.1.0-dev-2)
Provides an configuration endpoint for use in your Phoenix applications.
Rather than configuring your Electric Typescript
client directly, you
instead configure a route in your application with a pre-configured
Electric.Client.ShapeDefinition
and then retreive the URL and other
configuration for that shape from your client via a request to your Phoenix
application.
In your Phoenix application, add a route to
Electric.Phoenix.Gateway.Plug
specifying a particular shape:
defmodule MyAppWeb.Router do
scope "/shapes" do
pipe_through :browser
get "/todos", Electric.Phoenix.Gateway.Plug,
shape: Electric.Client.shape!("todos", where: "visible = true")
end
end
Then in your client code, you retrieve the shape configuration directly from the Phoenix endpoint:
import { ShapeStream } from '@electric-sql/client'
const endpoint = `https://localhost:4000/shapes/todos`
const response = await fetch(endpoint)
const config = await response.json()
// The returned `config` has all the information you need to subscribe to
// your shape
const stream = new ShapeStream(config)
stream.subscribe(messages => {
// ...
})
You can add additional authentication/authorization for shapes using
Phoenix's
pipelines or
other plug
calls.
Plug.Router
For pure Plug
-based applications, you can use Plug.Router.forward/2
:
defmodule MyRouter do
use Plug.Router
plug :match
plug :dispatch
forward "/shapes/items",
to: Electric.Phoenix.Gateway.Plug,
shape: Electric.Client.shape!("items")
match _ do
send_resp(conn, 404, "oops")
end
end
Parameter-based shapes
As well as defining fixed-shapes for a particular url, you can request shape configuration using parameters in your request:
defmodule MyAppWeb.Router do
scope "/" do
pipe_through :browser
get "/shape", Electric.Phoenix.Gateway.Plug, []
end
end
import { ShapeStream } from '@electric-sql/client'
const endpoint = `https://localhost:4000/shape?table=items&namespace=public&where=visible%20%3D%20true`
const response = await fetch(endpoint)
const config = await response.json()
// as before
The parameters are:
table
- The Postgres table name (required).namespace
- The Postgres schema if not specified defaults topublic
.where
- The where clause to filter items from the shape.
Summary
Functions
Callback implementation for Plug.call/2
.
Functions
Callback implementation for Plug.call/2
.