Elixir
View SourceThis page shows wasm_tools from Elixir. Everything else in these docs applies:
the functions are the same, called as :wasm_tools. examples/elixir/ is a Mix
project that runs every line below.
Add the dependency
defp deps do
[{:wasm_tools, "~> 0.1", hex: :erlang_wasm_tools}]
endLoad and call
Names and map keys are binaries, which in Elixir are strings:
{:ok, calc} = :wasm_tools.load({:file, "calculator.component.wasm"})
{:ok, 42} = :wasm_tools.call(calc, "add", %{"a" => 20, "b" => 22})
:ok = :wasm_tools.unload(calc)Values follow the table of Call a component: a record is a
map with string keys, a variant {"case", payload}, an option :none or
{:some, value}, a result {:ok, value} or {:error, value}.
{:ok, data} = :wasm_tools.load({:file, "data_transform.component.wasm"})
{:ok, {:ok, person}} =
:wasm_tools.call(data, "normalize", %{
"p" => %{"name" => " Ada ", "age" => 36, "email" => :none, "tags" => ["b", "a"]}
})
"Ada" = person["name"]Errors
Errors are maps with atom keys:
case :wasm_tools.call(calc, "add", %{"a" => 1}) do
{:ok, value} -> value
{:error, %{class: :argument, ctx: %{path: path}}} -> {:bad_argument, path}
endPut a registry in your supervision tree
children = [
:wasm_tools.child_spec(%{name: :tools, max_concurrency: 64})
]
Supervisor.start_link(children, strategy: :one_for_one)
{:ok, ["calc_add", "calc_multiply"]} = :wasm_tools.add(:tools, calc, %{namespace: "calc"})
{:ok, 42} = :wasm_tools.call(:tools, "calc_add", %{"a" => 20, "b" => 22})Host interfaces
A handler is a function of three arguments, or a module with handle/3:
kv = fn
"get", [key], _ctx -> {:some, "value of " <> key}
"put", [_key, _value], _ctx -> :undefined
end
{:ok, app} =
:wasm_tools.load({:file, "custom_host.component.wasm"},
%{host: %{"example:app/kv" => kv}})