Skip to content

Instantly share code, notes, and snippets.

@nickschot
Last active April 27, 2017 18:39
Show Gist options
  • Save nickschot/efa500efcb76cd64d068ca84f3d3e16d to your computer and use it in GitHub Desktop.
Save nickschot/efa500efcb76cd64d068ca84f3d3e16d to your computer and use it in GitHub Desktop.
Lux + Redis Middleware
// app/utils/redis.js
import { createClient } from 'then-redis';
export default createClient(process.env.REDIS_URL);
// app/middleware/redis.js
import redis from 'app/utils/redis';
/**
* Middleware to automatically cache routes to Redis.
* Initialize it in a beforeAction and afterAction hook.
* @param type Either 'beforeAction' or 'afterAction' to get the right middleware
* @param options
* @returns {*}
*/
export function getFromRedis(options = {}) {
return async (request, response) => {
const {
method,
action,
route: {
path
}
} = request;
if(method === 'GET' && (action === 'index' || action === 'show')){
const {
params
} = request;
const key = new Buffer
.from(path + JSON.stringify(params))
.toString('base64');
const payload = await redis.get(key);
if(payload){
return JSON.parse(payload);
} else {
request.cacheToRedis = key;
}
}
};
}
export function addToRedis(options = {}){
const {
expiresIn = 60
} = options;
return async (request, response, payload) => {
const {
cacheToRedis
} = request;
if(cacheToRedis){
redis.set(
cacheToRedis, JSON.stringify(payload),
'EX', expiresIn
);
}
return payload;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment