Search code examples
reactjsgraphqlrelayjsgraphql-js

React Relay: Adding data to edges


I'll first introduce my application: simple voting app where users can create and vote on polls. Simple.
Currently my graphql schema consists of user type, poll type and vote type, where the user and poll have one-to-many relation to its votes, using relay connection. The vote type contains, along with reference to its voter and poll, it's timestamp and the actual vote value.

Now, to my understanding, one of the advanges of using connections over regulations graphql lists is the ability to store data on the edge (in addition to pagination and more...). How could I do that?

If it is indeed possible, my plan is to get rid of the vote type, connect the user and his voted polls directly via connections, and storing the vote value and it's timestamp on the connecting edge.

If it's important, the connection between the voter and his polls should be bidirectional, i.e. each user is connected to his voted polls, and each poll is connected to its voters.


Solution

  • This is probably better modeled using a separate Vote entity as described in Michael Paris's answer, however, to address the more general question of "how do I define additional fields on an edge?", note that you can pass edgeFields into the connectionDefinitions function in the graphql-relay module.

    There's an example in the test suite:

    var {connectionType: friendConnection} = connectionDefinitions({
      name: 'Friend',
      nodeType: userType,
      resolveNode: edge => allUsers[edge.node],
      edgeFields: () => ({
        friendshipTime: {
          type: GraphQLString,
          resolve: () => 'Yesterday'
        }
      }),
      connectionFields: () => ({
        totalCount: {
          type: GraphQLInt,
          resolve: () => allUsers.length - 1
        }
      }),
    });