Last active
December 4, 2023 04:46
-
-
Save royanon/be212d7890eb6f4ae1b7447a1576c26b to your computer and use it in GitHub Desktop.
Graphql cache hint override for Strapi V4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Work on the following dependency | |
// "@strapi/strapi": "4.5", | |
// "@strapi/plugin-graphql": "4.5", | |
// "apollo-server-cache-redis": "^3.3.0", | |
// "apollo-server-core": "^3.3.0", | |
// "apollo-server-plugin-response-cache": "^3.3.0", | |
// file location: /src/index.js | |
'use strict'; | |
const MAX_AGE = parseInt(process.env.STRAPI_GRAPHQL_MAX_AGE? process.env.STRAPI_GRAPHQL_MAX_AGE : 60); | |
const MAX_AGE_DISABLE = 0; | |
// override those need a different max age | |
// customize cache scope, PUBLIC/PRIVATE | |
const customResolversConfig = () => { | |
const cache_control_matrix = [ | |
{ query: 'test1', maxAge: MAX_AGE_DISABLE, scope: "PRIVATE" }, | |
{ query: 'test2', maxAge: MAX_AGE, scope: "PRIVATE" }, | |
{ query: 'test3', maxAge: MAX_AGE, scope: "PUBLIC" } | |
]; | |
const resolversConfig = {}; | |
for (let i = 0; i < cache_control_matrix.length; i++) { | |
if (typeof cache_control_matrix[i] == "object") { | |
let middlewares = { | |
middlewares: [ | |
async (next, parent, args, context, info) => { | |
if (info && info.cacheControl) { | |
info.cacheControl.setCacheHint({ maxAge: cache_control_matrix[i].maxAge, scope: cache_control_matrix[i].scope }); | |
} | |
return next(parent, args, context, info); | |
} | |
] | |
} | |
let query = "Query." + cache_control_matrix[i].query; | |
resolversConfig[query] = middlewares; | |
} | |
} | |
return resolversConfig; | |
} | |
module.exports = { | |
/** | |
* An asynchronous register function that runs before | |
* your application is initialized. | |
* | |
* This gives you an opportunity to extend code. | |
*/ | |
register({ strapi }) { | |
const extensionService = strapi.plugin('graphql').service('extension'); | |
extensionService.use(({ nexus }) => ({ | |
resolvers: {}, | |
resolversConfig: customResolversConfig() | |
})); | |
}, | |
/** | |
* An asynchronous bootstrap function that runs before | |
* your application gets started. | |
* | |
* This gives you an opportunity to set up your data model, | |
* run jobs, or perform some special logic. | |
*/ | |
bootstrap() {}, | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The library is now available in here
https://github.com/10Life/strapi-plugin-advanced-cache-manager