Type Relations

Now we have a Book type and an Author type. We need to establish some type of relationship between the two. Every book has an author. And every author has a collection of books. To establish a relationshp we need someway in our data to be able to set this. We can do this by adding an authorId property to each book in our books collection. This authorId will have a value that matches the id of one of our authors.

Update your books dummy data to be:

// dummy data
const books = [
    { name: 'Name of the Wind', genre: 'Fantasy', id: '1', authorId: '1' },
    { name: 'The Final Empire', genre: 'Fantasy', id: '2', authorId: '2' },
    { name: 'The Long Earth', genre: 'Sci-Fi', id: '3', authorId: '3' },
    { name: 'The Hero of Ages', genre: 'Fantasy', id: '4', authorId: '2' },
    { name: 'The Colour of Magic', genre: 'Fantasy', id: '5', authorId: '3' },
    { name: 'The Light Fantastic', genre: 'Fantasy', id: '6', authorId: '3' }
];

Update Book Query

When you query on a book we want to also return the author. We can do this by updating our BookType query to add a field of author. This field is a object. The first thing we need to put in the object is the type. The type is AuthorType. Next we need to add a resolve function. We know the resolve function takes two parameters - parent and args. Instead of using args in our resolve function we are going to use parent. Parent points to the book object that is returned from the BookType query. That object has a field called authorId. We will use that in the resolve function to compare to the id in our authors dummy data to find the matching author.

const BookType = new GraphQLObjectType({
    name: 'Book',
    fields: () => ({
        id: { type: GraphQLID },
        name: { type: GraphQLString },
        genre: { type: GraphQLString },
        author: {
            type: AuthorType,
            resolve(parent, args) {
                return authors.find(author => author.id === parent.authorId);
            }
        }
    })
});

Query for Book and Author

Now that we have created our relationship between an Author and a Book let's test it out in a query. Challenge: Write a query that gets the book with id of 2 and also returns the nane of the author of the book. If you get stuck use the code below.

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

Bonus: You can also get the age of the author in your query.