Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
apollo-cache-control
Advanced tools
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.
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}`);
});
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 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.
This package is used to collect and expose cache control data in the Apollo Cache Control format.
It relies on instrumenting a GraphQL schema to collect cache control hints, and exposes cache control data for an individual request under extensions
as part of the GraphQL response.
This data can be consumed by Apollo Engine or any other tool to inform caching and visualize the cache policies that are in effect for a particular request.
Apollo Server includes built-in support for Apollo Cache Control from version 1.2.0 onwards.
The only code change required is to add tracing: true
and cacheControl: true
to the options passed to the Apollo Server middleware function for your framework of choice. For example, for Express:
app.use('/graphql', bodyParser.json(), graphqlExpress({
schema,
context: {},
tracing: true,
cacheControl: true
}));
If you are using
express-graphql
, we recommend you switch to Apollo Server. Bothexpress-graphql
and Apollo Server are based on thegraphql-js
reference implementation, and switching should only require changing a few lines of code.
Cache hints can be added to your schema using directives on your types and fields. When executing your query, these hints will be added to the response and interpreted by Engine to compute a cache policy for the response. Hints on fields override hints specified on the target type.
type Post @cacheControl(maxAge: 240) {
id: Int!
title: String
author: Author
votes: Int @cacheControl(maxAge: 30)
readByCurrentUser: Boolean! @cacheControl(scope: PRIVATE)
}
If you need to add cache hints dynamically, you can use a programmatic API from within your resolvers.
const resolvers = {
Query: {
post: (_, { id }, _, { cacheControl }) => {
cacheControl.setCacheHint({ maxAge: 60 });
return find(posts, { id });
}
}
}
If you're using TypeScript, you need the following:
import 'apollo-cache-control';
If set up correctly, for this query:
query {
post(id: 1) {
title
votes
readByCurrentUser
}
}
You should receive cache control data in the extensions
field of your response:
"cacheControl": {
"version": 1,
"hints": [
{
"path": [
"post"
],
"maxAge": 240
},
{
"path": [
"post",
"votes"
],
"maxAge": 30
},
{
"path": [
"post",
"readByCurrentUser"
],
"scope": "PRIVATE"
}
]
}
The power of cache hints comes from being able to set them precisely to different values on different types and fields based on your understanding of your implementation's semantics. But when getting started with Apollo Cache Control, you might just want to apply the same maxAge
to most of your resolvers. You can specify a default max age when you set up cacheControl
in your server. This max age will be applied to all resolvers which don't explicitly set maxAge
via schema hints (including schema hints on the type that they return) or the programmatic API. You can override this for a particular resolver or type by setting @cacheControl(maxAge: 0)
. For example, for Express:
app.use('/graphql', bodyParser.json(), graphqlExpress({
schema,
context: {},
tracing: true,
cacheControl: {
defaultMaxAge: 5,
},
}));
FAQs
A GraphQL extension for cache control
The npm package apollo-cache-control receives a total of 113,220 weekly downloads. As such, apollo-cache-control popularity was classified as popular.
We found that apollo-cache-control demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.