This is a proof of concept for apply query caching to the sequelize ORM using sequelize-redis, redis, and bluebird. The sequelize-redis package provides a wrapper for sequelize models which allows the use of cached methods. This gives us the flexibility to use regular sequelize queries or cached sequalize queries in our controllers.
Preferentially we should put the wrapper in a module to keep the codebase DRY.
The following is the module /config/cache.js
:
const SequelizeRedis = require('sequelize-redis');
const redis = require('redis');
const bluebird = require('bluebird');
// Let's promisify Redis
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
// Define your redisClient
const redisClient = redis.createClient({ /* Redis configuration comes here */ });
// Export the Wrapper
module.exports = new SequelizeRedis(redisClient);
In this repo we have the Playground model and controller. In the playground.js
controller we import:
const router = require('express').Router();
const { Playground } = require('../models');
const sequelizeRedis = require('../config/cache');
const PlaygroundModel = sequelizeRedis.getModel(Playground, { ttl: 3 });
With PlaygroundModel
we are using sequelize-redis to wrap the Playground Model.
Time to Live (ttl
) is the life time of the cache in seconds.
Either regular sequelize methods can be used or the new cached methods:
const id = req.params.id;
const cacheId = `id_${id}`;
// Using Caching to Find by Primary Key
const [dataRes, cacheHit] = await PlaygroundModel.findByPkCached(cacheId, id);
// NOT Using Caching to Find by Primary Key
const data = await PlaygroundModel.findByPk(id);
Results for the cached method:
dataRes
- regular sequelize responsecacheHit
- cache hit indication (boolean)
To use chaching methods, add the suffix "Cached" to the regular sequelize methods:
find
findOne
findAll
findAndCount
findAndCountAll
findByPk
all
min
max
sum
count
Use regular Redis API:
redisClient.del('SampleKey')
// '/'
- returns 'Hello World'
// '/playground'
- returns generic json
// '/playgorund/alldata'
- returns all data (not cached)
// '/playground/byid/:id'
- return data by id (cached)