Last active
April 13, 2020 10:01
-
-
Save gottfrois/5df513d6c02abcdef218e106ee7e976c to your computer and use it in GitHub Desktop.
Code snippet in Stream Paginated GraphQL API in Elixir medium blog post
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 MyApp.StreamPaginator do | |
def stream(query, args \\ %{first: 100}) do | |
init = fn -> request(query, args) end | |
next = &next/1 | |
stop = &Function.identity/1 | |
Stream.resource(init, next, stop) | |
end | |
defp request(query, args) do | |
query | |
|> HttpClient.post(%{variables: args}) | |
|> case do | |
{:ok, | |
%{"data" => %{"records" => %{"edges" => edges, "pageInfo" => page}}}} -> | |
{Enum.map(edges, & &1["node"]), page, query, args} | |
{:error, _reason} -> | |
{[], nil, query, args} | |
end | |
end | |
defp next({nil, _query, _args} = acc), do: {:halt, acc} | |
defp next({%{"hasNextPage" => false}, _query, _args} = acc), do: {:halt, acc} | |
defp next({%{"endCursor" => cursor}, query, args}) do | |
query | |
|> request(%{first: args[:first], after: cursor}) | |
|> next() | |
end | |
defp next({nodes, page, query, args}) do | |
{nodes, {page, query, args}} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment