首页 > 解决方案 > GraphQl null 从后端 Apollo 服务器检索数据

问题描述

嗨,我是 GraphQl 和 JavaScript 的新手。我有一个具有一些属性的书籍对象,包括每本书的作者。我想编写一个查询来返回由特定作者撰写的所有书籍,但我不能,从查询中得到的所有书籍都是空的,我搜索了几个小时似乎没有任何帮助。这是我的代码。谢谢你的帮助!。

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']
  },
]

这是我的 GraphQl 架构

const typeDefs = gql`

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

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

这是我的解析器,我试图从作者那里获取书籍。

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

最后,这就是我编写查询的方式。

query {
  allBooks(author: "Joshua Kerievsky") {
    title
  }
}

标签: javascriptgraphqlapollo-server

解决方案


这就是我修复它的方法。

 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,
      }
    }

推荐阅读