【问题标题】:Dynamic loading of fields动态加载字段
【发布时间】:2019-08-29 07:37:38
【问题描述】:

我正在使用 graphql-express lib 构建一个小型概念验证 GraphQL 服务器。让我们假设这个架构:

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

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

    type Query{
         book(id: ID!): Book
    }

这意味着我将能够通过 ID 为一本书而客户可以选择转移哪些字段。假设在服务器端加载作者是一个代价高昂的额外休息调用。因此,如果客户端不请求作者,我不希望解析器功能加载作者。谁能举例说明图书解析器功能是否确实必须加载作者并且仅在请求时才加载它?

谢谢!

【问题讨论】:

    标签: graphql


    【解决方案1】:

    解析器可让您定义仅在请求字段时才会执行的函数。

    所以我们可以在 Book 类型上为作者定义函数,在 Author 类型上为书籍定义函数,假设作者字段包含作者 ID,书籍包含书籍 ID 数组

    const resolvers = {
      Query: {
        // destruct id from args
        book: (root, { id }) => Book.getBookById(id),
      },
      // When we query for the Book type resolve the author field based on this function
      // if we dont query for the author field this function is not going to run
      // first argument is the parent document/record so we destruct author field
      // which will usually be the author id
      Book: {
        author: ({ author }) => Author.getAuthorById(author),
      },
      // Same as above when we request an Author type run this function
      // when books field is requested
      Author: {
        books: ({ books }) => Book.getBooksByIds(books),
      },
    };
    

    【讨论】:

    • 非常感谢,所有简单的示例都展示了如何创建模式,并且使用的解析器函数是 hello world ......我能够通过缝合/链接对象本身来创建我的模式,但是正在寻找上面这种更简单的方法。谢谢!
    猜你喜欢
    • 2016-09-06
    • 2020-03-07
    • 1970-01-01
    • 2023-03-26
    • 2017-06-10
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多