In Relay, what role do the node interface and the global ID spec play?

徘徊边缘 提交于 2019-11-28 03:27:24

The Node root field, in combination with globally unique IDs, comes into play when Relay needs to refetch an object. Refetching occurs when you call this.props.relay.forceFetch() or when you add fields to the query for an object whose global ID is known because it has already been partially fetched.

In cases like these, Relay will short circuit the regular query and execute a query for the object(s) directly using its global ID and the node root call.

Example:

Assume that $showComments was false when this query was first resolved.

query {
  viewer {
    stories(first: 10) {
      edges {
        node {
          id,
          comments(first: 10) @include(if: $showComments) { 
            author, 
            commentText 
          }
          text,
        }
      }
    }
  }
}

This will have caused a fetch for id and text for some number of stories, whose IDs are now known.

Imagine that at some future time, the variable $showComments became true. Relay will refetch only the data it needs using the node root field.

query {
  node(id: "ABC123") { 
    fragment on Story { comments(first: 10) { author, commentText } }
  }
  node(id: "DEF456") { 
    fragment on Story { comments(first: 10) { author, commentText } }
  }
  node(id: "GHI789") { 
    fragment on Story { comments(first: 10) { author, commentText } }
  }
  ...
}

This depends on a few pieces:

  1. Each object must have a globally unique ID, or be identified by a type/ID pair (the globalIdField helper does this and produces a base64 encoded string).
  2. The server must know how to resolve an object from a globally unique ID, and vice versa. This is what the nodeDefinitions are for.
  3. Any object that hopes to be refetchable using this system must implement the nodeInterface.

See also: https://facebook.github.io/relay/docs/graphql-object-identification.html#content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!