GraphQL Lists

Right now we have a one-way relationship between a book an an author. Next we want to create a relationship between an author and all the books they have written. You might thing we could just add a book ObjectType to Author but this will not work because an Author might have written more than one book. If we created a book ObjectType then this would return only one book. GraphQL provides a data type called GraphQLList to account for a collection in the data.

First we need to import the new data type of GraphQLList from graphql.

const {
    GraphQLObjectType,
    GraphQLString,
    GraphQLSchema,
    GraphQLID,
    GraphQLInt,
    GraphQLList
} = graphql;

Update AuthorType

Next we need to update the AuthorType to have a books object. The books object will be of type GraphQLList. The GraphQLList data type requires you to pass in a parameter of the data type. We will pass in BookType. In the resolve function we will want to find all books for this author. For that reason we cannot use the Array.find() method that we were previously using. Instead we will use the Array.filter method. Here is our updated AuthorType.

const AuthorType = new GraphQLObjectType({
    name: 'Author',
    fields: () => ({
        id: { type: GraphQLID },
        name: { type: GraphQLString },
        age: { type: GraphQLInt },
        books: {
            type: new GraphQLList(BookType),
            resolve(parent, args){
                return books.filter(book => book.authorId === parent.id);
            }
        }
    })
});

Create Author Query

Now that we have a relationship between an author and the books they have written we can create a query.

Challenge: Create a query that gets the author with an id of 2 and returns the name of all the books they have written. If you get stuck you can use the query below.

{
  author(id: "2") {
    name,
    books {
      name,
      genre
    }
  }
}

Bonus Modify the query to also include the genre for each book they have written.

Summary

We have now created a two way relationship between Books and Authors.