Skip to content

Instantly share code, notes, and snippets.

@jwerle
Created December 11, 2020 13:58
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwerle/53f2d86c835ceaa9448d6ba856e9fc6a to your computer and use it in GitHub Desktop.
Save jwerle/53f2d86c835ceaa9448d6ba856e9fc6a to your computer and use it in GitHub Desktop.
const apolloServerPluginResponseCache = require('apollo-server-plugin-response-cache')
const { RedisCache } = require('apollo-server-cache-redis')
// set this to whatever you believe should be the max age for your cache control
const MAX_AGE = 60
module.exports = {
federation: false,
apolloServer: {
tracing: 'production' !== strapi.config.environment ? true : false,
persistedQueries: { ttl: 10 * MAX_AGE }, // we set this to be a factor of 10, somewhat arbitrary
cacheControl: { defaultMaxAge: MAX_AGE },
plugins: [
apolloServerPluginResponseCache({
shouldReadFromCache,
shouldWriteToCache,
extraCacheKeyData,
sessionId,
}),
injectCacheControl()
]
}
}
if ('development' !== strapi.config.environment && process.env.REDIS_URL) {
const cache = new RedisCache(process.env.REDIS_URL)
module.exports.apolloServer.cache = cache
module.exports.apolloServer.persistedQueries.cache = cache
}
async function sessionId(requestContext) {
// return a session ID here, if there is one for this request
return null
}
async function shouldReadFromCache(requestContext) {
// decide if we should write to the cache in this request
return true
}
async function shouldWriteToCache(requestContext) {
// decide if we should write to the cache in this request
return true
}
async function extraCacheKeyData(requestContext) {
// use this to create any extra data that can be used for the cache key
}
function injectCacheControl() {
return {
requestDidStart(requestContext) {
requestContext.overallCachePolicy = {
scope: 'PUBLIC', // or 'PRIVATE'
maxAge: MAX_AGE,
}
}
}
}
@abett
Copy link

abett commented Aug 16, 2021

noted on strapi-forums as well, this works perfectly, but didn't on apollo-server-plugin-response-cache versions newer than 0.9.0
pinning the plugin version did fix my problems with the plugin being ignored by strapi's apollo server

@jwerle
Copy link
Author

jwerle commented Aug 16, 2021

thanks for the note!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment