Popcorn. Proxy
(Popcorn v0.4.0-next.2)
View Source
Connects JavaScript calls and casts to GenServers in the VM.
To receive them, add Popcorn.Proxy to your supervision tree.
Notes:
- One proxy handles concurrent requests to multiple GenServers.
- Targets can be registered names or PID handles from the same VM.
See Popcorn.Wasm 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 both processes to your application supervisor:
children = [MyApp.Counter, Popcorn.Proxy]
Supervisor.start_link(children, strategy: :one_for_one)After the VM boots, call the counter from JavaScript:
const result = await popcorn.genserver.call("counter", ["add", 1]);
if (!result.ok) throw result.error;
console.log(result.data); // 1
await popcorn.genserver.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.
Options
:name- the registered name. Defaults to:popcorn_proxy. JavaScript selects this name with itsproxyoption.