Backpex.PaginationValidation (Backpex v0.18.3)

Copy Markdown View Source

Validates pagination and sorting parameters from URL params.

Ensures invalid URL params don't crash the application and fall back to sensible defaults.

Validated Parameters

  • page - Page number (positive integer, defaults to 1)
  • per_page - Items per page (must be in allowed options)
  • order_by - Field to sort by (must be in orderable fields)
  • order_direction - Sort direction (must be :asc or :desc)

Summary

Functions

Builds validated pagination and sorting options from URL params.

Clamps a page number to valid range based on total pages.

Functions

build(params, opts)

Builds validated pagination and sorting options from URL params.

Returns a map with validated values. Invalid values are replaced with defaults.

Parameters

  • params - Map of URL params (string keys)
  • opts - Keyword list with:
    • :per_page_default - Default items per page (required)
    • :per_page_options - List of allowed per_page values (required)
    • :orderable_fields - List of field atoms that can be sorted (required)
    • :init_order - Map with :by and :direction defaults (required)

Returns

A map with validated values:

%{
  page: integer(),
  per_page: integer(),
  order_by: atom(),
  order_direction: :asc | :desc
}

Examples

iex> params = %{"page" => "2", "per_page" => "50", "order_by" => "title", "order_direction" => "desc"}
iex> opts = [
...>   per_page_default: 15,
...>   per_page_options: [15, 50, 100],
...>   orderable_fields: [:id, :title, :inserted_at],
...>   init_order: %{by: :id, direction: :asc}
...> ]
iex> Backpex.PaginationValidation.build(params, opts)
%{page: 2, per_page: 50, order_by: :title, order_direction: :desc}

# Invalid values fall back to defaults
iex> params = %{"page" => "invalid", "order_by" => "nonexistent"}
iex> opts = [per_page_default: 15, per_page_options: [15, 50, 100], orderable_fields: [:id, :title], init_order: %{by: :id, direction: :asc}]
iex> Backpex.PaginationValidation.build(params, opts)
%{page: 1, per_page: 15, order_by: :id, order_direction: :asc}

clamp_page(page, total_pages)

Clamps a page number to valid range based on total pages.

This is called after the initial validation once we know the total item count.

Examples

iex> Backpex.PaginationValidation.clamp_page(5, 3)
3
iex> Backpex.PaginationValidation.clamp_page(2, 5)
2
iex> Backpex.PaginationValidation.clamp_page(-1, 5)
1