Search code examples
graphqlrelayjsrelaygraphql-js

How to properly create the Id field on a graphql to be relay compliant?


I am following a relay+graphql tutorial and I cam confused with this code:

const GraphQLTodo = new GraphQLObjectType({
  name: 'Todo',
  fields: {
    id: globalIdField('Todo'),
    text: {
      type: GraphQLString,
      resolve: (obj) => obj.text, 
    },
    complete: {
      type: GraphQLBoolean,
      resolve: (obj) => obj.complete,
    },
  },
  interfaces: [nodeInterface],
});

On the resolve of text and complete field, where does the obj come from? is obj parameter from the query? and also, how do I resolve id from the query? do I do not have to resolve it? for example this is the id field code:

id: {
  id: globalIdField('Todo'),
  resolve: (obj) => obj.id, 
}

Will the above code work and isn't it redundant? how do I properly create the Id field to be relay compliant?


Solution

  • obj is the record itself, usually in whatever format you get from your persistent storage. In this case, it's a Todo object, with at least two properties: text and complete. This makes the resolve functions trivial. Resolve functions exist so you can do more complex things like the following:

    fullName: {
      type: GraphQLString,
      resolve: (obj) => obj.firstName + ' ' + obj.surname,
    }
    

    For the Relay compliant id, I don't think you need to do anything. globalIdField does it for you.