Skip to content

Instantly share code, notes, and snippets.

@h4cc
Created February 6, 2019 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h4cc/39cb684c7930cbb2c7f78f17d096fba0 to your computer and use it in GitHub Desktop.
Save h4cc/39cb684c7930cbb2c7f78f17d096fba0 to your computer and use it in GitHub Desktop.
Elixir Ecto paginate Query with callback
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