在 GraphQL 上查询包含非结构化对象的数组

Query an array with unstructured objects on GraphQL

我正在尝试使用 GraphQL 查询 Gridsome 中包含对象的非结构化数组。目前看起来很乱,感觉应该有更好的方法来做到这一点。

从 CMS 加载到 GraphQL 的数据如下所示:

{
    title: "Homepage",
    top_image: "imgurl.jpg",
    page_builder: [
             {
                 type: "slider",
                 field: "data example",
                 different_field: "data example"
             },
              {
                 type: "call_to_action",
                 field_for_cta: "data example",
                 different_cta_field: "data example"
             }
    ]
}

如您所见,page_builder 中的对象将具有不同的字段,具体取决于客户端构建此部分的方式。

当我尝试在 GraphQL 中查询时。会变得很乱:

<page-query>
query {
  data: pages(path: "/pages") {
    title,
    top_image,
    page_builder {
      type,
      field,
      different_field,
      type,
      field_for_cta,
      different_cta_field

      #this list will have way more fields depending on all the page builder elements

    }
    }
  }
</page-query>

有没有一种方法可以按类型组织这些字段,并且只组织 return 这种特定类型的字段?

假设gridsome支持片段,你可以这样做:

<page-query>
query {
  data: pages(path: "/pages") {
    title,
    top_image,
    page_builder {
      ...A @include(if: $includeA)
      ...B @include(if: $includeB)
      ...C @include(if: $includeC)
    }
  }
}

# Note: Replace PageBuilderType with appropriate type
fragment A on PageBuilderType {
  # your fields here
}
fragment B on PageBuilderType {
  # your fields here
}
fragment C on PageBuilderType {
  # your fields here
}
</page-query>

然后您可以在调用 createPage 时定义变量,如下所示 here:

api.createPages(({ createPage }) => {
    createPage({
      path: '/my-page',
      component: './src/templates/MyPage.vue',
      queryVariables: {
        includeA: someCondition,
        includeB: someCondition,
        includeC: someCondition,
      },
    })
  })
}