Skip to content

Instantly share code, notes, and snippets.

@sofyan-ahmad
Created March 24, 2021 03:51
Show Gist options
  • Save sofyan-ahmad/6896fa8b0c576a04d263ee7680bb9ce0 to your computer and use it in GitHub Desktop.
Save sofyan-ahmad/6896fa8b0c576a04d263ee7680bb9ce0 to your computer and use it in GitHub Desktop.
Strapi.io - Cache strapi on service level
// strapi/api/${YourModel}/services/${YourModel}
const crypto = require('crypto');
const redisClient = require('../../../cache/redis');
const sendNotification = require('./notification');
/**
* Read the documentation (https://strapi.io/documentation/v3.x/concepts/services.html#core-services)
* to customize this service
*/
const modelName = '${YourModel}';
const cachePrefix = 'cms:${YourModel}:';
module.exports = {
/**
* Promise to fetch all records
*
* @return {Promise}
*/
async find(params, populate) {
params._publicationState = params._publicationState || 'live';
const hash = crypto.createHash('sha1').update(JSON.stringify(params)).digest('base64');
const key = `${cachePrefix}list:${hash}`;
const fromCache = await redisClient.get(key);
if (fromCache) {
return JSON.parse(fromCache);
}
const result = await strapi.query(modelName).find(params, populate);
await redisClient.set(key, JSON.stringify(result));
return result;
},
/**
* Promise to fetch record
*
* @return {Promise}
*/
async findOne(params, populate) {
const hash = crypto.createHash('sha1').update(JSON.stringify(params)).digest('base64');
const key = `${cachePrefix}${hash}`;
const fromCache = await redisClient.get(key);
if (fromCache) {
return JSON.parse(fromCache);
}
const result = await strapi.query(modelName).findOne(params, populate);
await redisClient.set(key, JSON.stringify(result));
return result;
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment