Popcorn. Proxy
(Popcorn v1.0.0)
View Source
Connects JavaScript calls and casts to GenServers in the VM.
It's automatically started under the :popcorn application.
Starting one yourself and routing requests through it is a rare use-case (hooks, a large number of requests, etc).
Notes:
- One proxy handles concurrent requests to multiple GenServers.
- Targets can be registered names or PID handles from the same VM.
- In non-Wasm environments it returns
:ignorefromstart_link/1.
See Popcorn.JS for value conversions.
Example
Define a GenServer that accepts JavaScript requests:
defmodule MyApp.Counter do
use GenServer
def start_link(_opts), do: GenServer.start_link(__MODULE__, 0, name: :counter)
@impl true
def init(count), do: {:ok, count}
@impl true
def handle_call(["add", n], _from, count) do
{:reply, count + n, count + n}
end
@impl true
def handle_cast("reset", _count), do: {:noreply, 0}
endAdd the counter to your application supervisor:
children = [MyApp.Counter]
Supervisor.start_link(children, strategy: :one_for_one)After the VM boots, call the counter from JavaScript:
const result = await popcorn.call("counter", ["add", 1]);
console.log(result); // 1
await popcorn.cast("counter", "reset");Calls and casts
Calls wait for a reply, including deferred replies from GenServer.reply/2.
Calls report missing processes, server exits, replies that cannot be serialized, and timeouts.
The timeoutMs JavaScript option defaults to 5000. A timeout does not cancel the GenServer's work.
Casts are fire-and-forget.
Custom proxy names
Use {Popcorn.Proxy, name: :ui_proxy} in the supervision tree.
Select it in JavaScript with the option {proxy: "ui_proxy"}.
For multiple proxies under one supervisor, assign distinct child IDs with Supervisor.child_spec/2.
Summary
Functions
Returns a specification to start this module under a supervisor.
Starts a proxy linked to the current process.
Functions
Returns a specification to start this module under a supervisor.
See Supervisor.
@spec start_link(keyword()) :: GenServer.on_start()
Starts a proxy linked to the current process.
Returns :ignore outside WASM so supervisors can include the proxy on a native VM.
Options
:name- the registered name. Defaults to:popcorn_proxy. JavaScript selects this name with itsproxyoption.