在Apollo GraphQL中,我们可以在解析器中传递参数。为了将参数传递给查询的子类型,我们可以使用解析器参数中的第二个参数,即上下文对象。下面是一个示例代码:
// 在Schema定义中设置子类型
const typeDefs = `
type Query {
user(id: ID!): User
}
type User {
id: ID!
name: String
email: String
posts: [Post]
}
type Post {
id: ID!
title: String
content: String
author: User # User类型是Post的子类型
}
`;
// 定义解析器
const resolvers = {
Query: {
user: (parent, args, context) => {
return context.dataSources.Users.getUserById(args.id);
},
},
User: {
posts: (parent, args, context) => {
return context.dataSources.Posts.getPostsByUserId(parent.id);
},
},
Post: {
author: (parent, args, context) => {
return context.dataSources.Users.getUserById(parent.authorId);
},
},
};
// 挂载Apollo服务器
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
return {
dataSources: {
Users: new UserAPI(),
Posts: new PostAPI(),
},
};
},
});
在示例中,我们定义了一个包含User和Post类型的Schema。然后,我们在解析器中定义了三个函数,分别处理User和Post类型的字段以及查询。在这些函数中,我们使用上下文对象来访问数据源(UserAPI和PostAPI)并获取数据。最后,我们使用ApolloServer类将服务器挂载到端口上。
通过上述代码,我们可以很容易地将参数传递给查询的子类型。在这个例子中,我们使用上下文对象来访问数据源的方法并根据参数获取所需的子类型数据。