【问题标题】:GraphQL in Gatsbyjs - Only Return Data Which Contains a Particular FieldGatsbyjs 中的 GraphQL - 仅返回包含特定字段的数据
【发布时间】:2019-08-31 15:10:49
【问题描述】:

我在 GatsbyJs 框架中使用 GraphQL。

我有多个包含 JSON 数据的文件。数据的结构类似这样:

{
 ...,
 "sections" / "menuSections"
}

最后一个字段可以是每个文件中的“sections”或“menuSections”。我当前的 graphQL 查询如下所示:

{
  allDataJson {
    nodes {
      menuSections
    }
  }
}

此查询返回正确的“menuSections”,但是,没有“menuSections”的数据文件将返回为null。如何让 GraphQL 仅返回包含“menuSections”的文件中的数据,即如何返回存在“menuSections”的数据。我正在寻找像$exists 这样的运营商。

【问题讨论】:

    标签: json graphql gatsby graphql-js


    【解决方案1】:

    GraphQL 中似乎没有 $exists 运算符。相反,您可以做的是在解析器中添加一些逻辑来检查字段是否不为空。我发现了两个与您相关的老问题:
    GraphQL query and check the returned data
    GraphQL query: only include field if not null

    【讨论】:

      【解决方案2】:

      如果sections & menuSections 是字符串或字符串数​​组,也许你可以过滤null

      {
        "menuSections": "..."
      }
      
      // query
      {
        allDataJson(filter: {
          menuSections: {
            ne: null
          }
        }) {
          nodes {
            menuSections
          }
        }
      }
      

      如果它们是对象,您仍然可以过滤 null,但它必须应用于该对象内的字段之一。如果您的对象没有公共字段,这将不起作用:

      {
        "menuSections": {
          "menuSectionField": "..."
        }
      }
      
      // query
      {
        allDataJson(filter: {
          menuSections: {
            menuSectionField: {
              ne: null
            }
          }
        }) {
          nodes {
            menuSections
          }
        }
      }
      

      如果它们是对象数组,您可以使用elemMatch

      {
        "menuSections": [
          { "menuSectionField": "..." },
          { "other": "..." }
        ]
      }
      
      // query
      allDataJson(filter: {
          menuSections: {
            elemMatch: {
              menuSectionField: {
                ne: null
              }
            }
          }
        }) { ... }
      

      最坏的情况,我认为您可以定义某种自定义类型来确保 menuSections 的存在,以便您可以查询 allDataWithMenuSections 等,但如果过滤器有效,它会简单得多。

      【讨论】:

      • 一个精彩而全面的答案。感谢您满足各种场景。这解决了我的问题。
      • 这里是一个 graphql 新手 - filter 是 graphQL 固有支持的操作参数吗?!据我了解,在后端我们需要实际编写解析器来理解 filter 参数并相应地过滤数据。我似乎在这里遗漏了一块拼图。
      • @AnandUndavia 你是对的,这些过滤器功能是由 Gatsbyjs 实现的,它们不是 graphql 规范的一部分。我想我们应该更改问题标题以使其更清晰。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      • 2020-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 1970-01-01
      相关资源
      最近更新 更多