philomena/lib/philomena_web/plugs/pagination_plug.ex

53 lines
1.4 KiB
Elixir
Raw Normal View History

2019-11-17 19:18:21 +01:00
defmodule PhilomenaWeb.PaginationPlug do
2019-10-09 01:19:57 +02:00
import Plug.Conn
2019-11-30 23:40:53 +01:00
alias Pow.Plug
2019-10-09 01:19:57 +02:00
# No options
2019-11-30 23:40:53 +01:00
def init([]), do: []
2019-10-09 01:19:57 +02:00
# Assign pagination info
def call(conn, _opts) do
conn = conn |> fetch_query_params()
2019-11-30 23:40:53 +01:00
user = conn |> Plug.current_user()
2019-10-09 01:19:57 +02:00
params = conn.params
2019-12-20 22:12:47 +01:00
page_size = get_page_size(params)
page_number = get_page_number(params)
image_page_size = page_size || image_page_size(user)
comment_page_size = page_size || comment_page_size(user)
2019-10-09 01:19:57 +02:00
conn
2019-12-20 22:12:47 +01:00
|> assign(:pagination, %{page_number: page_number, page_size: page_size || 25})
|> assign(:image_pagination, %{page_number: page_number, page_size: image_page_size})
|> assign(:scrivener, [page: page_number, page_size: page_size || 25])
|> assign(:comment_scrivener, [page: page_number, page_size: comment_page_size])
end
defp get_page_number(%{"page" => page}) do
to_integer(page) || 1
end
defp get_page_number(_params), do: 1
defp get_page_size(%{"per_page" => per_page}) do
per_page
|> to_integer()
|> Kernel.||(25)
|> max(1)
|> min(50)
end
defp get_page_size(_params), do: nil
defp to_integer(string) do
case Integer.parse(string) do
{int, _rest} -> int
_ -> nil
end
2019-10-09 01:19:57 +02:00
end
2019-11-30 23:40:53 +01:00
defp image_page_size(%{images_per_page: x}), do: x
defp image_page_size(_user), do: 15
defp comment_page_size(%{comments_per_page: x}), do: x
defp comment_page_size(_user), do: 25
2019-10-09 01:19:57 +02:00
end