Skip to content

Instantly share code, notes, and snippets.

@royanon
Last active December 4, 2023 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save royanon/be212d7890eb6f4ae1b7447a1576c26b to your computer and use it in GitHub Desktop.
Save royanon/be212d7890eb6f4ae1b7447a1576c26b to your computer and use it in GitHub Desktop.
Graphql cache hint override for Strapi V4
// 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() {},
};
@royanon
Copy link
Author

royanon commented Dec 4, 2023

The library is now available in here https://github.com/10Life/strapi-plugin-advanced-cache-manager

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