Created
November 17, 2022 22:55
-
-
Save moroz/4d8b3af083745e7ec5afe13578a750f8 to your computer and use it in GitHub Desktop.
Pagination behavior for scrivener_ecto
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule UnterEats.Paginatable do | |
@callback base_query() :: Ecto.Queryable.t() | |
@callback filter_by_params({atom(), term()}, Ecto.Queryable.t()) :: Ecto.Queryable.t() | |
@optional_callbacks filter_by_params: 2 | |
alias UnterEats.Repo | |
def filter_and_paginate_resource(module, params) when is_atom(module) do | |
query = module.base_query() | |
params | |
|> Enum.reduce(query, &module.filter_by_params/2) | |
|> Repo.paginate(params) | |
end | |
defmacro __using__(resource_name) when is_atom(resource_name) do | |
function_name = :"filter_and_paginate_#{resource_name}" | |
quote do | |
@behaviour UnterEats.Paginatable | |
import Ecto.Query, warn: false | |
def filter_by_params(_, query), do: query | |
defoverridable filter_by_params: 2 | |
def unquote(function_name)(params), | |
do: UnterEats.Paginatable.filter_and_paginate_resource(__MODULE__, params) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment