How to define Relay fragment for GraphQLList of GraphQLObjectType?

507 views Asked by At

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')}
       }
    }`
  }
});
1

There are 1 answers

1
Ahmad Ferdous On BEST ANSWER

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.