Graphql 场的动态加载

Graphql 场的动态加载,graphql,Graphql,我正在使用graphql express库构建一个小型的概念验证graphql服务器。让我们假设这个模式: const typeDef = ` type Book { id: ID! title: String author: Author likes: Int } type Author { id: String name: String ag

我正在使用graphql express库构建一个小型的概念验证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查看一本书,客户可以选择传输哪些字段。让我们假设在服务器端加载作者是一个代价高昂的额外rest调用。因此,如果客户端不请求作者,我不希望解析器函数加载作者。有人能举一个例子,说明book resolver函数是否真的必须加载作者,并且只有在请求时才加载它


谢谢

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

因此,我们可以在作者的
Book
类型和书籍的
author
类型上定义函数,假设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),
  },
};

解析程序允许您定义仅在请求字段时执行的函数

因此,我们可以在作者的
Book
类型和书籍的
author
类型上定义函数,假设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),
  },
};

Thx这么多,所有简单的例子都展示了如何创建一个模式,使用的解析器函数都在那里。。。。我能够通过缝合/链接对象本身来创建我的模式,但我正在寻找上述更简单的方法。谢谢!Thx这么多,所有简单的例子都展示了如何创建一个模式,使用的解析器函数都在那里。。。。我能够通过缝合/链接对象本身来创建我的模式,但我正在寻找上述更简单的方法。谢谢!