Shouldn't variables be defined on fragment calls in GraphQL?

1.4k Views Asked by At

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?

1

There are 1 best solutions below

0
Herku On BEST ANSWER

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