在Apollo GraphQL中,字段的解析发生在GraphQL解析过程的不同阶段。在调用willResolveField
之前,字段会经历以下几个步骤:
解析查询文档:首先,GraphQL解析器会将查询文档解析为AST(抽象语法树),以便进一步处理。
构建查询计划:接下来,解析器会根据AST构建查询计划,该计划描述了如何执行查询。
执行字段解析:在执行查询计划时,解析器会逐个解析每个字段。这些字段可以是查询字段、对象字段或嵌套字段。
调用willResolveField
:在解析每个字段之前,Apollo GraphQL会调用willResolveField
函数。该函数可以添加字段级别的中间件,用于在解析字段之前执行某些操作。
下面是一个示例,展示如何在Apollo Server中使用willResolveField
函数添加字段级别的中间件:
const { ApolloServer } = require('apollo-server');
const { ApolloServerPluginInlineTrace } = require('apollo-server-core');
const typeDefs = `
type Query {
hello: String
users: [User]
}
type User {
id: ID
name: String
email: String
}
`;
const resolvers = {
Query: {
hello: () => 'Hello, world!',
users: () => [
{ id: 1, name: 'John', email: 'john@example.com' },
{ id: 2, name: 'Jane', email: 'jane@example.com' },
],
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
plugins: [
ApolloServerPluginInlineTrace({
willResolveField(_, { info }) {
console.log(`Resolving ${info.fieldName}`);
},
}),
],
});
server.listen().then(({ url }) => {
console.log(`Server running at ${url}`);
});
在上面的示例中,我们使用ApolloServerPluginInlineTrace
插件,并在其中定义了willResolveField
函数。该函数会在解析每个字段之前被调用,并打印出要解析的字段名。
运行上述代码后,当执行查询时,你会看到控制台输出类似于Resolving hello
和Resolving users
的信息,这表示willResolveField
函数被成功调用,字段解析发生在willResolveField
之前。