LightningWeb.Utils (Lightning v2.14.5-pre1)

View Source

Helper functions to deal with forms, query params, and dynamic plug setups.

This module contains:

Summary

Functions

Sets up multiple plugs using Replug.

Builds nested parameters for the given form field with the specified value.

Decodes a single {key, value} pair into a nested map suitable for query/form data.

Standard 503 Service Unavailable response for transient DB outages during webhook handling.

Functions

add_dynamic_plugs(plugs)

(macro)

Sets up multiple plugs using Replug.

Accepts a list of plug configurations, where each configuration is a tuple:

{PlugModule, opts}
  • PlugModule is the module implementing the plug.
  • opts can be a keyword list of options or a tuple like {module, function} for dynamic plug configuration.

This macro will iterate over the provided list, calling plug Replug, plug: plug, opts: opts for each item.

Examples

@pre_session_plugs Application.compile_env(:my_app, :pre_session_plugs, [])
add_dynamic_plugs(@pre_session_plugs)

build_params_for_field(form, field, value)

Builds nested parameters for the given form field with the specified value.

Internally:

  1. Obtains the param name for the field using Form.input_name(form, field).
  2. Uses decode_one/2 to decode the {param_name, value} tuple into a map.

Examples

iex> form = # some %Phoenix.HTML.Form{} struct
iex> LightningWeb.Utils.build_params_for_field(form, :username, "jane_doe")
%{"user" => %{"username" => "jane_doe"}}

decode_one(arg, acc \\ %{})

Decodes a single {key, value} pair into a nested map suitable for query/form data.

This function leverages Plug.Conn.Query.decode_each/2 and Query.decode_done/2 to parse the key and value into the expected nested structure.

If an accumulator (acc) is provided, it will merge the newly decoded structure into acc. Otherwise, a new map is returned.

Examples

iex> LightningWeb.Utils.decode_one({"user[username]", "jane_doe"})
%{"user" => %{"username" => "jane_doe"}}

iex> LightningWeb.Utils.decode_one({"user[username]", "jane_doe"}, %{"user" => %{"admin" => false}})
%{"user" => %{"admin" => false, "username" => "jane_doe"}}

noreply(socket)

ok(socket)

pluralize_with_s(n, string)

reply(socket)

respond_service_unavailable(conn, error, context, opts \\ [])

@spec respond_service_unavailable(
  Plug.Conn.t(),
  Exception.t(),
  map(),
  keyword()
) :: Plug.Conn.t()

Standard 503 Service Unavailable response for transient DB outages during webhook handling.

This function is typically called inside a with_webhook_retry/2 error branch when retries against the database have been exhausted.

Options

  • :message — custom response message, may include "%{s}" placeholder which will be replaced with the retry-after value.
  • :halt? — whether to halt the connection after sending the response. Defaults to true.