Squrler
Squrler

Reputation: 3514

Reusing a GraphQL query in another query without duplicating

Say I have two GraphQL queries.

Query A:

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

Query B:

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

Now I want both queries to contain another query:

Query C:

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

How do I do that without duplicating query C in both query A and B (which would not be very DRY)? You can only use fragments for pieces within one query if I understand correctly.

Update:

So I mean something like this:

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

and:

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

Upvotes: 3

Views: 1411

Answers (1)

Mohsen ZareZardeyni
Mohsen ZareZardeyni

Reputation: 956

You can define fragments on Query and Mutations and use them like this:

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
    }
  }
}

You can not define something like this tho!

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

Upvotes: 1

Related Questions