-1

Hi I'm new to GraphQl and JavaScript. I have an object of books with some properties including author of the each book. I want to write a query which returns all the books written by a specific author but I couldn't, all am getting from the query is null, and I searched for hours nothing seems like helpful. Here is my code. Thanks for your help!.

let books = [
  {
    title: 'Clean Code',
    published: 2008,
    author: 'Robert Martin',
    id: "afa5b6f4-344d-11e9-a414-719c6709cf3e",
    genres: ['refactoring']
  },
  {
    title: 'Agile software development',
    published: 2002,
    author: 'Robert Martin',
    id: "afa5b6f5-344d-11e9-a414-719c6709cf3e",
    genres: ['agile', 'patterns', 'design']
  },
]

This is my GraphQl Schema

const typeDefs = gql`

  type Book {
    title: String!
    published: Int!
    author: String!
    id: ID!
    genres: [String!]!
  }

  type Query {
    bookCount: Int!
    allBooks(author: String!): Book
  }
`

And here is my resolver where am trying to get the books by the author.

const resolvers = {
  Query: {
    allBooks: (root, args) => {
    books.map(book => book.author === args.author)
        console.log(args.author);
    },
    bookCount: () => books.length,
  }
}

And finally, this is how I write the query.

query {
  allBooks(author: "Joshua Kerievsky") {
    title
  }
}
Nasir_001
  • 29
  • 8

1 Answers1

0

This is how I fixed it.

 const resolvers = {
      Query: {
        allBooks: (root, args) => {
        const booksToReturn = books.filter(book => book.author === args.author)
            console.log(booksToReturn);
        },
        allAuthor: () => authors,
        authorCount: () => authors.length,
        bookCount: () => books.length,
      }
    }
Nasir_001
  • 29
  • 8