在Apollo中,可以使用@cacheControl
指令来控制缓存机制,从而避免GraphQL解析多态关联。
以下是一个示例解决方法:
interface Node {
id: ID!
}
type User implements Node {
id: ID!
name: String!
}
type Post implements Node {
id: ID!
title: String!
author: User!
}
@cacheControl
指令来控制缓存:const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
interface Node {
id: ID!
}
type User implements Node {
id: ID!
name: String!
}
type Post implements Node {
id: ID!
title: String!
author: User!
}
type Query {
post(id: ID!): Post
}
`;
const resolvers = {
Node: {
__resolveType(obj, context, info) {
// 解析节点类型
if (obj.title) {
return 'Post';
}
if (obj.name) {
return 'User';
}
return null;
},
},
Query: {
post(_, { id }) {
// 模拟从数据库获取帖子数据
const post = getPostById(id);
return post;
},
},
Post: {
author(parent) {
// 模拟从数据库获取作者数据
const author = getUserById(parent.authorId);
return author;
},
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
cacheControl: {
defaultMaxAge: 3600, // 默认缓存1小时
},
});
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});
在上述示例中,我们使用__resolveType
函数来解析Node接口的实现类型。然后,我们在Post
类型的author
字段解析器中获取作者数据。通过使用@cacheControl
指令,我们可以设置缓存的最大生命周期,并自动避免解析多态关联时的重复请求。
请注意,上述示例中的getPostById
和getUserById
函数是模拟从数据库中获取数据的示例函数。根据实际情况,你需要替换这些函数来获取真实的数据。
上一篇:Apollo占用100%CPU