2

I'm trying to find out how to use arguments on nested items in my query using Absinthe.

What I try to accomplish is this:

{
  users(order: ASC) {
    id
    email
    clients(order: DESC) {
      id
      email
    }
  }
}

Here's my Schema and Type:

  query do
    @desc "Get all users"
    field :users, list_of(:user) do
      arg :order, type: :sort_order, default_value: :asc
      resolve &Resolvers.users/2
    end
  end

  @desc "A user"
  object :user do
    field :id, :id
    field :email, :string
    field :clients, list_of(:user)
  end  

And the resolver:

  def users(_, args, _) do
    args
    |> Enum.reduce(User, fn
      {:order, order}, query ->
        query |> order_by({^order, :email})
    end)
    |> Repo.all |> Repo.preload([:clients])
  end

So my question is how and where should I place the sorting argument for the clients? With the above example I get an error:

"message": "Unknown argument \"order\" on field \"clients\" of type \"User\"."
Fabien Sa
  • 9,135
  • 4
  • 37
  • 44
Gulliver
  • 103
  • 1
  • 8
  • This [Q & A](https://stackoverflow.com/questions/34155439/getting-error-unknown-argument-id-on-field-user-of-type-query-graphql?rq=1) might have something to help you. – Onorio Catenacci Oct 10 '17 at 14:45

1 Answers1

5

Put the argument under the clients field:

object :user do
  field :id, :id
  field :email, :string
  field :clients, list_of(:user) do
    arg :order, type: :sort_order, default_value: :asc
    resolve &Resolvers.clients/2
  end
end 

Then write a resolver to handle the sorting:

def clients(user, %{order: clients_order}, _) do
  sorted_clients = user.clients # TODO sort those clients into the desired order
  {:ok, sorted_clients}
end
Asker
  • 173
  • 1
  • 9