HexPort.Facade (hex_port v0.17.0)

Copy Markdown View Source

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()]
end

MyApp.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
end

Options

  • :contract — the contract module that defines port operations via use HexPort.Contract and defport declarations. Defaults to __MODULE__ (combined contract + facade).
  • :otp_app (required) — the OTP application name for config-based dispatch. Implementations are resolved from Application.get_env(otp_app, contract)[:impl].
  • :test_dispatch? — controls whether the generated facade includes the NimbleOwnership-based test handler resolution step. Accepts true, false, or a zero-arity function returning a boolean. The function is evaluated at compile time. Defaults to fn -> Mix.env() != :prod end, so production builds get a config-only dispatch path with zero NimbleOwnership overhead.

Configuration

# config/config.exs
config :my_app, MyApp.Todos, impl: MyApp.Todos.Ecto

Testing

# 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