Created
February 6, 2019 09:31
-
-
Save h4cc/39cb684c7930cbb2c7f78f17d096fba0 to your computer and use it in GitHub Desktop.
Elixir Ecto paginate Query with callback
This file contains hidden or 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 MyEcto do | |
# Helper to paginate a query | |
def paginate_query(%Ecto.Query{} = query, per_page, current_page, callback) when per_page > 0 and current_page >= 0 and is_function(callback) do | |
import Ecto.Query | |
offset = per_page * current_page | |
query | |
|> limit(^per_page) | |
|> offset(^offset) | |
|> LongRepo.all() | |
|> case do | |
[] -> | |
:ok | |
results -> | |
Enum.each(results, &(callback.(&1))) | |
if(length(results) >= per_page) do | |
paginate_query(query, per_page, current_page+1, callback) | |
else | |
:ok | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment