Hash :
4d8f6ed5
Author :
Thomas de Grivel
Date :
2022-11-02T18:24:08
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
## kmxgit
## Copyright 2022 kmx.io <contact@kmx.io>
##
## Permission is hereby granted to use this software granted
## the above copyright notice and this permission paragraph
## are included in all copies and substantial portions of this
## software.
##
## THIS SOFTWARE IS PROVIDED "AS-IS" WITHOUT ANY GUARANTEE OF
## PURPOSE AND PERFORMANCE. IN NO EVENT WHATSOEVER SHALL THE
## AUTHOR BE CONSIDERED LIABLE FOR THE USE AND PERFORMANCE OF
## THIS SOFTWARE.
defmodule Kmxgit.Pagination do
import Ecto.Query
alias Kmxgit.IndexParams
alias Kmxgit.Repo
def query(query, %IndexParams{page: page, per: per}) do
query
|> limit(^per + 1)
|> offset(^(per * (page - 1)))
end
def page(query, params = %IndexParams{page: page, per: per}, preload: preload) do
result = query
|> query(params)
|> preload(^preload)
|> Repo.all()
first_page = if page > 2, do: 1
prev_page = if page > 1, do: page - 1
{next_page, result} = if length(result) > per do
{page + 1, Enum.slice(result, 0..-2)}
else
{nil, result}
end
count = Repo.one(from(t in subquery(query), select: count("*")))
count_pages = Float.ceil(count / per) |> trunc()
last_page = if (page < count_pages - 1), do: count_pages
first = if count > 0, do: (page - 1) * per + 1, else: 0
last = if count > 0, do: first + length(result) - 1, else: 0
%{count: count,
count_pages: count_pages,
first: first,
first_page: first_page,
last: last,
last_page: last_page,
next_page: next_page,
page: page,
per: per,
prev_page: prev_page,
result: result}
end
end