如何在Elixir中使用Absinthe在我的查询中使用嵌套项的参数?

时间:2017-10-08 14:47:11

标签: elixir phoenix-framework graphql absinthe

我正在尝试使用Absinthe找出如何在查询中使用嵌套项的参数。

我试图完成的是:

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

这是我的架构和类型:

  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  

解析器:

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

所以我的问题是我应该如何以及在何处为客户放置排序参数? 通过上面的例子我得到一个错误:

"message": "Unknown argument \"order\" on field \"clients\" of type \"User\"."

1 个答案:

答案 0 :(得分:4)

将参数放在clients字段下:

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 

然后写一个解析器来处理排序:

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