What is apollo-cache-control?
The apollo-cache-control npm package is used to provide fine-grained cache control for GraphQL responses in Apollo Server. It allows developers to specify cache hints directly in the schema or resolvers, which can then be used to control the caching behavior of responses.
What are apollo-cache-control's main functionalities?
Setting Cache Hints in Schema
This feature allows you to set cache hints directly in the GraphQL schema using the @cacheControl directive. In this example, the 'books' query has a cache hint with a maxAge of 60 seconds.
const { ApolloServer, gql } = require('apollo-server');
const { ApolloServerPluginCacheControl } = require('apollo-server-core');
const typeDefs = gql`
type Query {
books: [Book] @cacheControl(maxAge: 60)
}
type Book {
title: String
author: String
}
`;
const resolvers = {
Query: {
books: () => [
{ title: 'The Awakening', author: 'Kate Chopin' },
{ title: 'City of Glass', author: 'Paul Auster' }
]
}
};
const server = new ApolloServer({
typeDefs,
resolvers,
plugins: [ApolloServerPluginCacheControl({ defaultMaxAge: 5 })]
});
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
Setting Cache Hints in Resolvers
This feature allows you to set cache hints programmatically within resolvers. In this example, the 'books' resolver sets a cache hint with a maxAge of 60 seconds using the context.cacheControl.setCacheHint method.
const { ApolloServer, gql } = require('apollo-server');
const { ApolloServerPluginCacheControl } = require('apollo-server-core');
const typeDefs = gql`
type Query {
books: [Book]
}
type Book {
title: String
author: String
}
`;
const resolvers = {
Query: {
books: (parent, args, context) => {
context.cacheControl.setCacheHint({ maxAge: 60 });
return [
{ title: 'The Awakening', author: 'Kate Chopin' },
{ title: 'City of Glass', author: 'Paul Auster' }
];
}
}
};
const server = new ApolloServer({
typeDefs,
resolvers,
plugins: [ApolloServerPluginCacheControl({ defaultMaxAge: 5 })]
});
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
Other packages similar to apollo-cache-control
graphql-cache
graphql-cache is a package that provides caching capabilities for GraphQL queries. It allows you to cache responses based on query and variables, and it integrates with various caching backends. Compared to apollo-cache-control, graphql-cache focuses more on the caching mechanism itself rather than providing fine-grained cache control hints.
dataloader
dataloader is a generic utility for batching and caching data-fetching operations. While it is not specifically designed for GraphQL, it is commonly used in GraphQL servers to optimize data fetching. Unlike apollo-cache-control, which provides cache hints for responses, dataloader focuses on reducing redundant data fetching and improving performance through batching and caching.