philomena/lib/philomena_web/plugs/pagination_plug.ex

57 lines
1.4 KiB
Elixir
Raw Permalink 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
# 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 = fetch_query_params(conn)
user = conn.assigns.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})
2020-01-11 05:20:19 +01:00
|> assign(:scrivener, page: page_number, page_size: page_size || 25)
|> assign(:comment_scrivener, page: page_number, page_size: comment_page_size)
2019-12-20 22:12:47 +01:00
end
defp get_page_number(%{"page" => page}) do
2020-09-08 05:19:32 +02:00
page
|> to_integer()
|> Kernel.||(1)
|> max(1)
2019-12-20 22:12:47 +01:00
end
2020-01-11 05:20:19 +01:00
2019-12-20 22:12:47 +01:00
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
2020-01-11 05:20:19 +01:00
2019-12-20 22:12:47 +01:00
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