Caravela.Live.OnMount (Caravela v0.8.0)

Copy Markdown View Source

on_mount callback that assembles the per-request context map the generated Caravela contexts expect (%{current_user: ..., tenant: ...}) and assigns it to socket.assigns.context.

Every generated LiveView currently re-rolls its own build_context/1 and threads context through each context call. Plugging this on_mount in lets the whole LiveView read from @context instead:

defmodule MyAppWeb.Library.BookLive.Index do
  use MyAppWeb, :live_view
  on_mount Caravela.Live.OnMount

  def mount(_params, _session, socket) do
    {:ok, assign(socket, :books, MyApp.Library.list_books(socket.assigns.context))}
  end
end

Keys pulled from socket.assigns:

  • :current_user — always included when present, otherwise nil.
  • :tenant — included when present. Mirrors the generated build_context/1 shape for multi-tenant domains.

Extra keys can be folded in by calling put/3 from your own on_mount callback (defined after this one), or by setting extra assigns on the socket before this hook runs.

Summary

Functions

Phoenix.LiveView on_mount hook. Wires :current_user and :tenant from the socket into the :context assign. Always returns {:cont, socket} — it never blocks a mount.

Merge overrides into the context map currently on socket. Useful from a follow-up on_mount to stamp values this hook doesn't know about (api keys, request ids, feature-flag snapshots, …).

Functions

on_mount(atom, params, session, socket)

Phoenix.LiveView on_mount hook. Wires :current_user and :tenant from the socket into the :context assign. Always returns {:cont, socket} — it never blocks a mount.

put(socket, key, value)

Merge overrides into the context map currently on socket. Useful from a follow-up on_mount to stamp values this hook doesn't know about (api keys, request ids, feature-flag snapshots, …).

on_mount {Caravela.Live.OnMount, :default}
on_mount fn _, _, _, socket ->
  {:cont, Caravela.Live.OnMount.put(socket, :request_id, Logger.metadata()[:request_id])}
end