1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Pagination do
7 Implements Mastodon-compatible pagination.
17 def fetch_paginated(query, params, type \\ :keyset)
19 def fetch_paginated(query, %{"total" => true} = params, :keyset) do
20 total = Repo.aggregate(query, :count, :id)
24 items: fetch_paginated(query, Map.drop(params, ["total"]), :keyset)
28 def fetch_paginated(query, params, :keyset) do
29 options = cast_params(params)
32 |> paginate(options, :keyset)
34 |> enforce_order(options)
37 def fetch_paginated(query, %{"total" => true} = params, :offset) do
38 total = Repo.aggregate(query, :count, :id)
42 items: fetch_paginated(query, Map.drop(params, ["total"]), :offset)
46 def fetch_paginated(query, params, :offset) do
47 options = cast_params(params)
50 |> paginate(options, :offset)
54 def paginate(query, options, method \\ :keyset)
56 def paginate(query, options, :keyset) do
58 |> restrict(:min_id, options)
59 |> restrict(:since_id, options)
60 |> restrict(:max_id, options)
61 |> restrict(:order, options)
62 |> restrict(:limit, options)
65 def paginate(query, options, :offset) do
67 |> restrict(:order, options)
68 |> restrict(:offset, options)
69 |> restrict(:limit, options)
72 defp cast_params(params) do
82 Enum.reduce(params, %{}, fn
83 {key, _value}, acc when is_atom(key) -> Map.drop(acc, [key])
84 {key, value}, acc -> Map.put(acc, key, value)
87 changeset = cast({%{}, param_types}, params, Map.keys(param_types))
91 defp restrict(query, :min_id, %{min_id: min_id}) do
92 where(query, [q], q.id > ^min_id)
95 defp restrict(query, :since_id, %{since_id: since_id}) do
96 where(query, [q], q.id > ^since_id)
99 defp restrict(query, :max_id, %{max_id: max_id}) do
100 where(query, [q], q.id < ^max_id)
103 defp restrict(query, :order, %{min_id: _}) do
104 order_by(query, [u], fragment("? asc nulls last", u.id))
107 defp restrict(query, :order, _options) do
108 order_by(query, [u], fragment("? desc nulls last", u.id))
111 defp restrict(query, :offset, %{offset: offset}) do
112 offset(query, ^offset)
115 defp restrict(query, :limit, options) do
116 limit = Map.get(options, :limit, @default_limit)
122 defp restrict(query, _, _), do: query
124 defp enforce_order(result, %{min_id: _}) do
129 defp enforce_order(result, _), do: result