在Apollo Server中,可以通过定义嵌套字段解析器来处理GraphQL查询中的嵌套字段。以下是一个解决方法,其中包含代码示例:
const { gql } = require('apollo-server');
const typeDefs = gql`
type Book {
id: ID
title: String
author: Author
}
type Author {
id: ID
name: String
books: [Book]
}
type Query {
books: [Book]
authors: [Author]
}
`;
module.exports = typeDefs;
const books = [
{ id: '1', title: 'Book 1', authorId: '1' },
{ id: '2', title: 'Book 2', authorId: '1' },
{ id: '3', title: 'Book 3', authorId: '2' },
];
const authors = [
{ id: '1', name: 'Author 1' },
{ id: '2', name: 'Author 2' },
];
module.exports = { books, authors };
const { books, authors } = require('./data');
const resolvers = {
Query: {
books: () => books,
authors: () => authors,
},
Book: {
author: (parent) => authors.find(author => author.id === parent.authorId),
},
Author: {
books: (parent) => books.filter(book => book.authorId === parent.id),
},
};
module.exports = resolvers;
const { ApolloServer } = require('apollo-server');
const typeDefs = require('./schema');
const resolvers = require('./resolvers');
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`Apollo Server is running at ${url}`);
});
这样,你就可以使用Apollo Server中的嵌套字段解析器来解析GraphQL查询中的嵌套字段了。在上面的示例中,我们定义了Book类型和Author类型,并在解析器中处理了相关的嵌套字段解析逻辑。例如,当查询books字段时,解析器会返回所有的图书,并在每本书中解析与之相关的作者信息。同样,当查询authors字段时,解析器会返回所有的作者,并在每个作者中解析与之相关的图书信息。