Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a list of custom objects in GraphQL

I am currently playing around with a bunch of new technology of Facebook.

I have a little problem with GraphQL schemas. I have this model of an object:

{
        id: '1',
        participants: ['A', 'B'],
        messages: [
            {
                content: 'Hi there',
                sender: 'A'
            },
            {
                content: 'Hey! How are you doing?',
                sender: 'B'
            },
            {
                content: 'Pretty good and you?',
                sender: 'A'
            },
        ];
    }

Now I want to create a GraphQL model for this. I did this:

var theadType = new GraphQLObjectType({
  name: 'Thread',
  description: 'A Thread',
  fields: () => ({
    id: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'id of the thread'
    },
    participants: {
      type: new GraphQLList(GraphQLString),
      description: 'Participants of thread'
    },
    messages: {
      type: new GraphQLList(),
      description: 'Messages in thread'
    }

  })
});

I know there are more elegant ways to structure the data in the first place. But for the sake of experimenting, I wanted to try it like this.

Everything works fine, besides my messages array, since I do not specify the Array type. I have to specify what kind of data goes into that array. But since it is an custom object, I don't know what to pass into the GraphQLList().

Any idea how to resolve this besides creating an own type for messages?

like image 658
MoeSattler Avatar asked Aug 23 '15 12:08

MoeSattler


1 Answers

You can define your own custom messageType the same way you defined theadType, and then you do new GraphQLList(messageType) to specify the type of your list of messages.

like image 132
Peter Hilton Avatar answered Oct 26 '22 22:10

Peter Hilton