首页 > 解决方案 > 在另一个查询中重用 GraphQL 查询而不重复

问题描述

假设我有两个 GraphQL 查询。

查询一:

{
  entry(section: [privacyStatement]) {
    ... on PrivacyStatement {
      title
      slug
      pageTitle
      metaDescription
      metaImage {
        id
        title
        url
      }
    }
  }
}

查询 B:

{
  entry(section: [contact]) {
    ... on Contact {
      title
      slug
      pageTitle
      metaDescription
      metaImage {
        id
        title
        url
      }
    }
  }
}

现在我希望两个查询都包含另一个查询:

查询 C:

  {
    services: categories(groupId: 1, level: 1) {
      id
      title
      slug
      children {
        id
        title
        slug
      }
    }
  }

如何在查询 A 和 B 中不复制查询 C 的情况下做到这一点(这不会很干燥)?如果我理解正确,您只能在一个查询中使用片段。

更新:

所以我的意思是这样的:

Query A {
  entry(section: [privacyStatement]) {
    ... on PrivacyStatement {
      title
      slug
      pageTitle
      metaDescription
      metaImage {
        id
        title
        url
      }
    }
  }
}
QueryC

和:

Query B {
  entry(section: [contact]) {
    ... on Contact {
      title
      slug
      pageTitle
      metaDescription
      metaImage {
        id
        title
        url
      }
    }
  }
}
QueryC

标签: graphql

解决方案


您可以在 Query 和 Mutations 上定义片段并像这样使用它们:

Query A {
  entry(section: [privacyStatement]) {
    ... on PrivacyStatement {
      title
      slug
      pageTitle
      metaDescription
      metaImage {
        id
        title
        url
      }
    }
  }
  ...C
}

fragment C on Query {
  services: categories(groupId: 1, level: 1) {
    id
    title
    slug
    children {
      id
      title
      slug
    }
  }
}

你不能定义这样的东西!

query A(...){...}
query B(...){...}

推荐阅读