Generates a dispatch facade for a HexPort.Contract.
use HexPort.Facade reads a contract's __port_operations__/0 metadata
and generates facade functions, bang variants, and key helpers that
dispatch via HexPort.Dispatch.
Combined contract + facade (simplest)
When :contract is omitted, it defaults to __MODULE__ and
use HexPort.Contract is issued implicitly. This gives a single-module
contract + facade:
defmodule MyApp.Todos do
use HexPort.Facade, otp_app: :my_app
defport get_todo(id :: String.t()) :: {:ok, Todo.t()} | {:error, term()}
defport list_todos() :: [Todo.t()]
endMyApp.Todos is both the contract (has @callbacks, __port_operations__/0)
and the dispatch facade.
Separate contract and facade
For cases where you want the contract in a different module:
defmodule MyApp.Todos do
use HexPort.Facade, contract: MyApp.Todos.Contract, otp_app: :my_app
endOptions
:contract— the contract module that defines port operations viause HexPort.Contractanddefportdeclarations. Defaults to__MODULE__(combined contract + facade).:otp_app(required) — the OTP application name for config-based dispatch. Implementations are resolved fromApplication.get_env(otp_app, contract)[:impl].:test_dispatch?— controls whether the generated facade includes theNimbleOwnership-based test handler resolution step. Acceptstrue,false, or a zero-arity function returning a boolean. The function is evaluated at compile time. Defaults tofn -> Mix.env() != :prod end, so production builds get a config-only dispatch path with zeroNimbleOwnershipoverhead.
Configuration
# config/config.exs
config :my_app, MyApp.Todos, impl: MyApp.Todos.EctoTesting
# test/test_helper.exs
HexPort.Testing.start()
# test/my_test.exs
setup do
HexPort.Testing.set_fn_handler(MyApp.Todos, fn
:get_todo, [id] -> {:ok, %Todo{id: id}}
:list_todos, [] -> []
end)
:ok
end
test "gets a todo" do
assert {:ok, %Todo{}} = MyApp.Todos.get_todo("42")
end