frenzy/lib/frenzy/paginator.ex

29 lines
637 B
Elixir

defmodule Frenzy.Paginator do
import Ecto.Query
alias Frenzy.{Repo, Item}
@spec paginate(query :: Ecto.Queryable.t(), params :: map()) :: Ecto.Query.t()
def paginate(query, %{"before" => before_id}) do
before = Repo.get(Item, before_id)
query
# |> where([o], o.id < ^before_id)
|> where([i], i.date < ^before.date)
|> order_by(desc: :date)
end
def paginate(query, %{"after" => after_id}) do
after_item = Repo.get(Item, after_id)
query
|> where([i], i.date > ^after_item.date)
|> order_by(asc: :date)
end
def paginate(query, _) do
query
|> order_by(desc: :date)
end
end