X-Git-Url: http://git.squeep.com/?a=blobdiff_plain;f=lib%2Fpleroma%2Fpagination.ex;h=9d279fba7939f12256d57cf41261f0e506fba562;hb=139b1feda122a8828a562c127989c8778a817308;hp=7c864deef8feb05b79d8001bba03389c94e77294;hpb=b92a16aa006dd7ec26397b6fcd111c8f8f843a9c;p=akkoma diff --git a/lib/pleroma/pagination.ex b/lib/pleroma/pagination.ex index 7c864deef..9d279fba7 100644 --- a/lib/pleroma/pagination.ex +++ b/lib/pleroma/pagination.ex @@ -1,3 +1,7 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2019 Pleroma Authors +# SPDX-License-Identifier: AGPL-3.0-only + defmodule Pleroma.Pagination do @moduledoc """ Implements Mastodon-compatible pagination. @@ -10,16 +14,46 @@ defmodule Pleroma.Pagination do @default_limit 20 - def fetch_paginated(query, params) do + def fetch_paginated(query, params, type \\ :keyset) + + def fetch_paginated(query, %{"total" => true} = params, :keyset) do + total = Repo.aggregate(query, :count, :id) + + %{ + total: total, + items: fetch_paginated(query, Map.drop(params, ["total"]), :keyset) + } + end + + def fetch_paginated(query, params, :keyset) do options = cast_params(params) query - |> paginate(options) + |> paginate(options, :keyset) |> Repo.all() |> enforce_order(options) end - def paginate(query, options) do + def fetch_paginated(query, %{"total" => true} = params, :offset) do + total = Repo.aggregate(query, :count, :id) + + %{ + total: total, + items: fetch_paginated(query, Map.drop(params, ["total"]), :offset) + } + end + + def fetch_paginated(query, params, :offset) do + options = cast_params(params) + + query + |> paginate(options, :offset) + |> Repo.all() + end + + def paginate(query, options, method \\ :keyset) + + def paginate(query, options, :keyset) do query |> restrict(:min_id, options) |> restrict(:since_id, options) @@ -28,14 +62,28 @@ defmodule Pleroma.Pagination do |> restrict(:limit, options) end + def paginate(query, options, :offset) do + query + |> restrict(:order, options) + |> restrict(:offset, options) + |> restrict(:limit, options) + end + defp cast_params(params) do param_types = %{ min_id: :string, since_id: :string, max_id: :string, + offset: :integer, limit: :integer } + params = + Enum.reduce(params, %{}, fn + {key, _value}, acc when is_atom(key) -> Map.drop(acc, [key]) + {key, value}, acc -> Map.put(acc, key, value) + end) + changeset = cast({%{}, param_types}, params, Map.keys(param_types)) changeset.changes end @@ -60,6 +108,10 @@ defmodule Pleroma.Pagination do order_by(query, [u], fragment("? desc nulls last", u.id)) end + defp restrict(query, :offset, %{offset: offset}) do + offset(query, ^offset) + end + defp restrict(query, :limit, options) do limit = Map.get(options, :limit, @default_limit)