3

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

1 Answer 1

1

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(...){...}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer; I'm not sure this covers what I mean. What I meant is, is there a way to re-use Query C within Query A and Query B, without adding Query C explicitly to Query A and B. I've updated the question.
:D Thank you. I'll just have to repeat the query then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.