1

I'm new to GraphQL. I was going through the documentation and found something which I feel is odd.

The way to pass data to variables in fragments is to do it through the root query the fragments are part of. The example given in the docs is repeated here for convenience.

query HeroComparison($first: Int = 3) {
  leftComparison: hero(episode: EMPIRE) {
    ...comparisonFields
  }
  rightComparison: hero(episode: JEDI) {
    ...comparisonFields
  }
}

fragment comparisonFields on Character {
  name
  friendsConnection(first: $first) {
    totalCount
    edges {
      node {
        name
      }
    }
  }
}

My question is, why does HeroComparison define the parameter to be passed down to the enclosed fragments and not the fragments directly? We use the variables in the fragments, so shouldn't it be something like this?

query HeroComparison {
  leftComparison: hero(episode: EMPIRE) {
    ...comparisonFields($first: Int = 3)
  }
  rightComparison: hero(episode: JEDI) {
    ...comparisonFields($first: Int = 3)
  }
}

fragment comparisonFields on Character {
  name
  friendsConnection(first: $first) {
    totalCount
    edges {
      node {
        name
      }
    }
  }
}

Since this is repetitive, we may even do something like

query HeroComparison {
  leftComparison: hero(episode: EMPIRE) {
    ...comparisonFields
  }
  rightComparison: hero(episode: JEDI) {
    ...comparisonFields($first: Int = 2)
  }
}

fragment comparisonFields on Character {
  *var $first: Int
  name
  friendsConnection(first: $first = 3) {
    totalCount
    edges {
      node {
        name
      }
    }
  }
}

My main concern in asking this is what if we wanted the first instantiation of comparisonFields to get the value 3 and the second to get 2 in the same query?

The docs page mentioned nothing to this end.

Also, aren't the second and third approaches better from the standpoint of separation of concerns?

StackMatch
  • 99
  • 1
  • 12
  • according to specs - https://spec.graphql.org/June2018/#sec-Validation.Variables ... variables are defined for OPERATION (in short declared only in outer query/mutation ... within 'body' you can only 'consume variables'/use $values) ... you can use aliases to query with different values (define two vars, one for each aliased query) – xadm Nov 17 '20 at 01:00
  • Hi @xadm thank you for replying. While I can see what you mean, doesn't that defeat the benefit that GraphQL brings over REST? – StackMatch Nov 17 '20 at 01:15
  • which one? still possible what you want ... still much more flexible than rest – xadm Nov 17 '20 at 01:24

1 Answers1

0

Pros and Cons of your approach are discussed in detail in this issue.

Herku
  • 7,198
  • 27
  • 36