Skip to content

Commit

Permalink
Add offset support for listing pages and counting pages (#381)
Browse files Browse the repository at this point in the history
* Add offset support when listing pages

* Add page counting function

* Add sort option
  • Loading branch information
ChristianTovar authored Dec 15, 2023
1 parent be5b137 commit c73bd9b
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions lib/beacon/content.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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`.
Expand Down

0 comments on commit c73bd9b

Please sign in to comment.