10

New expression @relay(pattern: true) was introduced in change log for relay.js 0.5.

But can't figure out from description nor tests what exactly it does and when I should use it when writing fatQueries.

Some example would be very helpful.

YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
Jarda
  • 1,188
  • 1
  • 7
  • 12

1 Answers1

7

Consider a GraphQL query like the following:

viewer {
  friends(first: 10) {
    totalCount
    edges { node { name } }
    pageInfo { hasNextPage }
  }
}

When defining a fat query for a Relay mutation, to include the name of a field without specifying any of its subfields tells Relay that any subfield of that field could change as a result of that mutation.

Unfortunately, to omit connection arguments such as find, first, and last on the friends field will cause a validation error on the connection-argument-dependent fields edges and pageInfo:

getFatQuery() {
  return Relay.QL`
    fragment on AddFriendMutationPayload {
      viewer { 
        friends { edges, pageInfo }  # Will throw the validation error below
      }
    }
  `;
}

// Uncaught Error: GraphQL validation/transform error ``You supplied the `pageInfo` 
// field on a connection named `friends`, but you did not supply an argument necessary 
// to do so. Use either the `find`, `first`, or `last` argument.`` in file 
// `/path/to/MyMutation.js`.

You can use the @relay(pattern: true) directive to indicate that want to use the fat query to pattern match against the tracked query, instead of to use it as a fully-fledged query.

getFatQuery() {
  return Relay.QL`
    fragment on AddFriendMutationPayload @relay(pattern: true) {
      viewer {
        friends { edges, pageInfo }  # Valid!
      }
    }
  `;
}

For more information about mutations see: https://facebook.github.io/relay/docs/guides-mutations.html#content

steveluscher
  • 4,144
  • 24
  • 42
  • Hmmm... I thought this happened automatically. Quoting from the above doc link: `This fat query looks like any other GraphQL query, with one important distinction. We know some of these fields to be non-scalar (like friendEdge and friends) but notice that we have not named any of their children by way of a subquery. In this way, we indicate to Relay that anything under those non-scalar fields may change as a result of this mutation.` – Kyle Mathews Dec 06 '15 at 00:39
  • 1
    Hunh. I wrote those docs too. I'm going to have to phone-a-friend on this one. @JoeSavona, what _is_ the pattern directive for? – steveluscher Dec 06 '15 at 03:25
  • Phoned a friend. Editing my answer! – steveluscher Dec 06 '15 at 06:02
  • We're going to have to update the mutations guide. https://github.com/facebook/relay/issues/647 – steveluscher Dec 06 '15 at 06:17
  • The answer to my previous question https://github.com/facebook/relay/issues/1300 and https://github.com/facebook/relay/pull/1376 – Dmitry Minkovsky Dec 11 '16 at 13:46