Last active
April 27, 2017 18:39
-
-
Save nickschot/efa500efcb76cd64d068ca84f3d3e16d to your computer and use it in GitHub Desktop.
Lux + Redis Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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