node.js express.js sequelize redis cache
const to = require(‘await-to-js’).default;
const Redis = require(‘ioredis’);
const redis = new Redis(ooxxooxx);
function Cache() {}
Cache.get = async function(key) {
const [err, res] = await to(redis.get(key));
if (err) {console.error(‘REDIS::Cache::get]’, err); return null;}
return JSON.parse(res);
};
Cache.set = async function(key, value) {
value = JSON.stringify(value);
const [err] = await to(redis.set(key, value));
if (err) {console.error(‘REDIS::Cache::set]’, err); }
};
//
// sequelize.query
//
async function CacheSequelizeQuery(sequelize, sql, params, redisKey) {
const cacheData = await Cache.get(redisKey);
if (cacheData) return cacheData; // not empty return cache data
const [err, lists] = await to(sequelize.query(sql, params));
if (err) throw err;
if (lists) await Cache.set(redisKey, lists); // not empty set cache data
return lists;
}
//
// findOneCache
//
Sequelize.Model.findOneCache = async function() {
let redisKey;
for (const parms of Object.values(arguments)) {
if (parms.where) redisKey = [this.name, JSON.stringify(parms.where)].join(':');
}
const cacheValue = await Cache.get(redisKey);
if (cacheValue) return JSON.parse(cacheValue);
const result = await Sequelize.Model.findOne.apply(this, arguments);
Cache.set(redisKey, JSON.stringify(result));
return result;
};