Get All Books and Authors

Right now we have queries that return information for a single book or a single author. What if we wanted to get all the books in the database or all the authors in the database? To do that we will need to create a new RootQuery. In the RootQuery add a new entry for books. This will be of type GraphQLList of BookType. The resolve function will return the entire books array. We will also add a new entry for authors. It will be a type of GraphQLList of AuthorType. The resolve function will return the entire authors array.

Add new RootQuery

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        book: {
            type: BookType,
            args: { id: { type: GraphQLID }},
            resolve(parent, args) {
                // code to get data from db / other source
                return books.find(book => book.id === args.id);
            }
        },
        author: {
            type: AuthorType,
            args: { id: { type: GraphQLID }},
            resolve(parent, args) {
                // code to get data from db / other source
                return authors.find(author => author.id === args.id);
            }
        },
        books: {
            type: new GraphQLList(BookType),
            resolve(parent, args) {
                // code to get data from db / other source
                return books;
            }
        },
        authors: {
            type: new GraphQLList(AuthorType),
            resolve(parent, args) {
                // code to get data from db / other source
                return authors;
            }
        }
    }
});

Test Our New Queries

Challenge: Test a query in graphiql that will return the name of all books as well as the name of the Author. Also create a query that will return the name of all authors and the name of all books that they have written. If you get stuck use the query below.

{
  books {
    name
    author {
      name
    }
  }
}
{
  authors {
    name
    books {
      name
    }
  }
}