Skip to content

Instantly share code, notes, and snippets.

@LawJolla
Created April 10, 2017 23:44
Show Gist options
  • Save LawJolla/600ee13f42c9dfd9beda449c05a5ebed to your computer and use it in GitHub Desktop.
Save LawJolla/600ee13f42c9dfd9beda449c05a5ebed to your computer and use it in GitHub Desktop.
Absinthe Root Query Pagination
defmodule WkGraphql.Schema do
use Absinthe.Schema
import_types WkGraphql.Schema.Types
query do
@desc "Get a user"
field :user, :user do
arg :id, non_null(:integer)
resolve &WkGraphql.UserResolver.find/2
end
@desc "Get all users"
field :users, list_of(:user) do
resolve &WkGraphql.UsersResolver.all/2
end
# field :threads_list, :threads do
# resolve &WkGraphql.MessageResolver.find_all_threads/2
# end
# @desc "Get all message threads"
# field :threads, list_of(:thread) do
# resolve &WkGraphql.MessageResolver.find_all_threads/2
# end
connection field :threads, node_type: :thread do
arg :first, non_null(:integer)
arg :last, :string
resolve fn
p_args, %{source: thread, context: %{uuid: uuid, current_user: user}} ->
thread_id = get_thread_id(thread)
with thread <- Messages.find_all_threads_query(thread, user, uuid),
connection <- Absinthe.Relay.Connection.from_query(thread, &WkGraphql.Repo.all/1, p_args) do
{:ok, connection}
else
{:error, error} -> {:error, error}
_ -> {:error, "Error fetching Threads"}
end
end
end
@desc "Find a thread"
field :thread, :thread do
arg :thread_id, non_null(:integer)
resolve &WkGraphql.MessageResolver.find_thread_by_id/2
end
end
end
@pierreabreup
Copy link

so bad, I've got the follwing error:

expected a map, got: {:ok, %{edges: [], page_info: %{end_cursor: nil, has_next_page: false, has_previous_page: false, start_cursor: nil}}}

@LawJolla Do you know what can be wrong?

@pierreabreup
Copy link

pierreabreup commented Dec 27, 2018

Solved! I have to return Absinthe.Relay.Connection.from_query(thread, &WkGraphql.Repo.all/1, p_args) directly

resolve fn
  p_args, %{source: thread, context: %{uuid: uuid, current_user: user}} ->
    Messages.find_all_threads_query(thread, user, uuid)
    |> Absinthe.Relay.Connection.from_query(&WkGraphql.Repo.all/1, p_args)
end

It is worth noting source: threadis unecessary because you are list the root object. You have to use source when you are listing associated object ( https://hexdocs.pm/absinthe_relay/Absinthe.Relay.Connection.html#module-connection )

object :person do
  field :first_name, :string
  connection field :pets, node_type: :pet do
    resolve fn
      pagination_args, %{source: person} ->
        Absinthe.Relay.Connection.from_list(
          Enum.map(person.pet_ids, &pet_from_id(&1)),
          pagination_args
        )
      end
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment