【问题标题】:Creating a GraphQL field without a resolver在没有解析器的情况下创建 GraphQL 字段
【发布时间】:2019-09-28 14:48:43
【问题描述】:

我正在将 Elixir 与 Phoenix 和 Absinthe 一起使用来设置 GraphQL 后端。

理想情况下,我希望有一个如下所示的结构:

{
  posts {
    published {
      title
    }
    draft {
      title
    }
  }
}

为此,我认为我需要将架构中的posts 字段委托给响应publisheddraft 的对象。我是这样做的:

# In my Schema
field :posts, type: :posts_by_state

# In my Post type definitions
object :post do
  # ...
end

object :posts_by_state do
  field :published, list_of(:post) do
    resolve fn _, _, _ -> ... end
  end

  field :draft, list_of(:post) do
    resolve fn _, _, _ -> ... end
  end
end

这不起作用,而是为整个 posts 字段返回 null。但是,如果我将架构中的 posts 字段更改为包含“空白”解析器,它会按预期工作:

field :posts, type: :posts_by_state do
  resolve fn _, _, _ -> {:ok, []} end
end

这是最佳实践还是有更好的方法来告诉字段完全委托给对象?更一般地说,有没有更好的方法来构建它?

【问题讨论】:

    标签: elixir graphql phoenix-framework absinthe


    【解决方案1】:

    此答案由 Benwilson512 在 Elixir 论坛上提供。在这里发帖分享答案


    您在此处看到的行为是预期的,尽管您使用的虚拟解析器通常是:

    field :posts, type: :posts_by_state do
      resolve fn _, _, _ -> {:ok, %{}} end
    end
    

    如果您不指定解析器,Absinthe 将使用默认解析器,即 Map.get(parent_value, field_name)。在您的情况下,如果根值是%{}(默认情况下),那么如果您没有指定帖子字段解析器,Absinthe 会执行Map.get(%{}, :posts),这当然会返回nil。由于该字段返回nil,因此不会执行任何子字段。

    实际上,这些看起来更像是 IE 的参数:

    {
      published: posts(status: PUBLISHED) { title }
      draft: posts(status: DRAFT) { title }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-03
      • 2020-05-11
      • 2019-12-13
      • 1970-01-01
      • 2018-10-27
      • 2011-08-23
      • 1970-01-01
      • 2020-10-07
      相关资源
      最近更新 更多