简体   繁体   中英

How to define Relay fragment for GraphQLList of GraphQLObjectType?

I've got a graphql-java implementation and a schema defined. Is it possible to create a field of type GraphQLList(SomeGraphQLObjectType) in a GraphQL query and use it in a Relay.QL {} declaration fragment, so I can receive a list of the desired object? Is this the place where Relay "Connections" work?

export default Relay.createContainer(ChildComponent, {
  fragments: {
    item: () => Relay.QL`
      fragment on Item
      {
        id,
        name,
        color{
          id,
          name
        }
      }`
  }});


export default Relay.createContainer(ParentComponent, {
  fragments: {
    list: () => Relay.QL`
    fragment on ListOfItems{
       allItems
       {
         ${ChildComponent.getFragment('item')}
       }
    }`
  }
});

Is it possible to create a field of type GraphQLList(SomeGraphQLObjectType) in a GraphQL query and use it in a Relay.QL {} declaration fragment?

Yes, it's possible with the help of @relay(plural: true) directive. It tells Relay that this field is a list, instead of a single item.

Define the field like this, where Item is a GraphQLObjectType with the same name :

itemList: {
  type: new GraphQLList(Item),
  // other stuff including resolve function
},

Since you have divided your Relay containers as parent and child, define the parent container like this:

export default Relay.createContainer(ParentComponent, {
  fragments: {
    itemList: () => Relay.QL`
      fragment on Item @relay(plural:true) {
        ${ChildComponent.getFragment('item')}
      }
    `,
  },
});

and the child container like this:

export default Relay.createContainer(ChildComponent, {
  fragments: {
    item: () => Relay.QL`
      fragment on Item {
        id,
        name,
        color {
          id,
          name,
        }
      }
    `,
  },
});

You can learn more about Relay directives in this article by Clay Allsopp.

There's a similar question which you can take a look at too.

Is this the place where Relay "Connections" work?

It depends. If you do not want all items in one shot, then connection is the way to go. It enables fetching data incrementally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM