PhoenixKitAI.Web.SortHelpers (PhoenixKitAI v0.3.0)

Copy Markdown View Source

Shared URL-param parsing for the AI admin LVs (endpoints.ex, prompts.ex, plus the usage tab inside endpoints).

Each LV passes its allowed sort-field whitelist + the sort default

  • (optionally) the direction default; the helper validates and falls back to those defaults on malformed input.

Summary

Functions

Coerces page to a positive integer (default 1 for nil / empty / invalid input).

Coerces dir to :asc / :desc. Unknown input returns default.

Returns field as an atom if it appears in valid_fields, otherwise default. Non-binary inputs return the default directly.

Parses sort / dir / page URL params into a canonical {sort_by, sort_dir, page} tuple. Sort field is cast via String.to_existing_atom/1 after a whitelist check, so an unrecognised value can't allocate a new atom.

Functions

parse_page(p)

@spec parse_page(any()) :: pos_integer()

Coerces page to a positive integer (default 1 for nil / empty / invalid input).

parse_sort_dir(arg1, default)

@spec parse_sort_dir(any(), :asc | :desc) :: :asc | :desc

Coerces dir to :asc / :desc. Unknown input returns default.

parse_sort_field(field, valid_fields, default)

@spec parse_sort_field(any(), [String.t()], atom()) :: atom()

Returns field as an atom if it appears in valid_fields, otherwise default. Non-binary inputs return the default directly.

parse_sort_params(params, opts)

@spec parse_sort_params(
  map(),
  keyword()
) :: {atom(), :asc | :desc, pos_integer()}

Parses sort / dir / page URL params into a canonical {sort_by, sort_dir, page} tuple. Sort field is cast via String.to_existing_atom/1 after a whitelist check, so an unrecognised value can't allocate a new atom.

Options

  • :valid_fields — list of binary field names allowed by the caller (e.g. ~w(name inserted_at sort_order)). Required.
  • :default_sort — atom returned when sort is absent or invalid. Required.
  • :default_dir — direction returned when dir is absent or unrecognised. Default :asc.