在Apollo GraphQL中,可以使用@cacheControl
指令来为特定字段或解析器添加缓存配置。
以下是一个示例,演示如何使用动态缓存模式类型来为字段添加缓存配置:
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book] @cacheControl(maxAge: 3600)
}
`;
const resolvers = {
Query: {
books: () => {
// 这里可以是从数据库或其他数据源获取数据的逻辑
return [
{
title: 'Book 1',
author: 'Author 1'
},
{
title: 'Book 2',
author: 'Author 2'
},
];
}
}
};
const server = new ApolloServer({
typeDefs,
resolvers
});
server.listen().then(({ url }) => {
console.log(`Server running at ${url}`);
});
在上面的示例中,我们在books
字段上使用@cacheControl(maxAge: 3600)
指令,指定了该字段的缓存最大有效期为3600秒(1小时)。
通过这种方式,我们可以对不同的字段或解析器使用不同的缓存配置,而不是应用于整个解析器。