【问题标题】:Write resolvers for nested type definitions为嵌套类型定义编写解析器
【发布时间】:2019-08-28 23:50:28
【问题描述】:

假设我的 GraphQL API 有以下类型定义:

const typeDef = `
    type Book {
         title: String
         author: Author
         likes: Int
    }

    type Author {
         id: String
         name: String
         age: Int
         books: [Book]
    }

    type Query{
         books(authorid: String!): Book
    }
`

那么,我需要多少个解析器呢?我应该只使用一个解析器books 处理此查询请求并返回所有书籍和作者信息,还是应该创建多个解析器,例如Query -> booksBook -> authorAuthor -> books?我不确定模块化架构和解析器如何协同工作。

【问题讨论】:

    标签: graphql graphql-js apollo-server express-graphql graphql-tools


    【解决方案1】:

    无论您使用多少类型(书籍、作者等)或输入,您都需要提供。

    const schema = ` 
        type Mutation {
            mutatePost(postId:Int) :Int
        }
        type Query {
            hello: String
            posts: [String]
            books(authorId: String!): Book
        }
      `
    

    您需要使用与您在解析器中定义的查询相同的名称

       const resolvers = {
            Query: {
            async hello() {
                return 'Hello';
            },
            async posts() {
                return ['Hello', 'World];
            },
            async books(_, { authorId }) {
                //Return data which you is defined in type Book
                //return Book
            }
            },
            Mutation: {
                async mutatePost(_, {
                postId
                }, context) {
                //return Integer
                }
            },
        }
    

    只有每个 Query 和 Mutation 需要 queryResolver 和 mutationResolver

    【讨论】:

    • 难道我们不应该为Book -> author 类型编写解析器吗?
    • 在查询或突变中使用它们之前,无需为它们编写解析器。
    • 我在查询返回类型中也使用了type Booktype Author
    • 您是说书籍:书籍还是作者:作者,那么您还需要为书籍和作者编写解析器。
    猜你喜欢
    • 2018-12-22
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    相关资源
    最近更新 更多