我正在使用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识别一本书,客户可以选择要转移的字段。假设在服务器端加载作者是一个代价高昂的额外休息。因此,如果客户端不请求作者,则我不希望解析器功能加载作者。谁能举个例子说明图书解析器功能是否确实需要加载作者并仅在需要时才加载?
thx!
答案 0 :(得分:2)
使用解析程序,您可以定义仅在请求字段时才执行的功能。
因此,我们可以针对作者的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),
},
};