From c73bd9be23e304196e7205a223f38dec814f9b92 Mon Sep 17 00:00:00 2001 From: Christian Tovar Date: Fri, 15 Dec 2023 08:12:04 -0500 Subject: [PATCH] Add offset support for listing pages and counting pages (#381) * Add offset support when listing pages * Add page counting function * Add sort option --- lib/beacon/content.ex | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/lib/beacon/content.ex b/lib/beacon/content.ex index cc25c100..3f01f829 100644 --- a/lib/beacon/content.ex +++ b/lib/beacon/content.ex @@ -748,35 +748,40 @@ defmodule Beacon.Content do ## Options * `:per_page` - limit how many records are returned, or pass `:infinity` to return all records. + * `:offset` - offsets the number of rows selected from the result. * `:query` - search pages by path or title. * `:preloads` - a list of preloads to load. + * `:sort` - column in which the result will be ordered by. """ @doc type: :pages @spec list_pages(Site.t(), keyword()) :: [Page.t()] def list_pages(site, opts \\ []) do per_page = Keyword.get(opts, :per_page, 20) + offset = Keyword.get(opts, :offset, 0) search = Keyword.get(opts, :query) preloads = Keyword.get(opts, :preloads, []) + sort = Keyword.get(opts, :sort, :title) site |> query_list_pages_base() |> query_list_pages_limit(per_page) + |> query_list_pages_offset(offset) |> query_list_pages_search(search) |> query_list_pages_preloads(preloads) + |> query_list_pages_sort(sort) |> Repo.all() end - defp query_list_pages_base(site) do - from p in Page, - where: p.site == ^site, - order_by: [asc: p.order, asc: fragment("length(?)", p.path)] - end + defp query_list_pages_base(site), do: from(p in Page, where: p.site == ^site) defp query_list_pages_limit(query, limit) when is_integer(limit), do: from(q in query, limit: ^limit) defp query_list_pages_limit(query, :infinity = _limit), do: query defp query_list_pages_limit(query, _per_page), do: from(q in query, limit: 20) + defp query_list_pages_offset(query, offset) when is_integer(offset), do: from(q in query, offset: ^offset) + defp query_list_pages_offset(query, _offset), do: from(q in query, offset: 0) + defp query_list_pages_search(query, search) when is_binary(search) do from(q in query, where: ilike(q.path, ^"%#{search}%") or ilike(q.title, ^"%#{search}%")) end @@ -789,6 +794,18 @@ defmodule Beacon.Content do defp query_list_pages_preloads(query, _preloads), do: query + defp query_list_pages_sort(query, sort), do: from(q in query, order_by: [asc: ^sort]) + + @doc """ + Counts the total number of pages based on the amount of pages. + """ + @spec count_pages(Site.t()) :: integer() + def count_pages(site) do + query = from p in Page, where: p.site == ^site, select: count(p.id) + + Repo.one(query) + end + @doc """ Returns all published pages for `site`.