Last active
March 16, 2018 15:35
-
-
Save lukaszjanyga/91d581223ecefd4ed2744d9f0638c7ca to your computer and use it in GitHub Desktop.
Simple redis cache
This file contains hidden or 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
async function getAuthResponse(req) { | |
let serviceRes = await cacheController.getCachedCustomerAuth(req.headers.authorization); | |
if (serviceRes === null) { | |
serviceRes = await CustomerService.isAuthenticated(req); | |
cacheController.cacheCustomerAuth(req.headers.authorization, serviceRes); | |
} | |
return serviceRes; | |
} |
This file contains hidden or 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
const RedisClient = require('./redis_client'); | |
const hydra = require('hydra-express').getHydra(); | |
const KEY_CACHE = 'cache'; | |
class CacheController { | |
/** | |
* @param {RedisClient} redisClient | |
*/ | |
constructor(redisClient) { | |
this._redisClient = redisClient; | |
} | |
cacheCustomerAuth(token, customerResponse) { | |
this._redisClient.cacheValue(this._formatCacheKey(token), JSON.stringify(customerResponse)); | |
} | |
getCachedCustomerAuth(token) { | |
return this._redisClient.getCachedValue(this._formatCacheKey(token)).then(JSON.parse); | |
} | |
_formatCacheKey(key) { | |
return `${KEY_CACHE}:${hydra.getServiceName()}:${key}`; | |
} | |
} | |
module.exports = new CacheController(new RedisClient()); |
This file contains hidden or 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
const redis = require('redis'); | |
const config = require('../config.json'); | |
const REDIS_CONFIG = config['hydra']['redis']; | |
const CACHE_EXPIRE_SEC = 3600; | |
class RedisClient { | |
constructor() { | |
this._client = redis.createClient(REDIS_CONFIG['url']); | |
} | |
cacheValue(key, value) { | |
this._client.setex(key, CACHE_EXPIRE_SEC, value); | |
} | |
getCachedValue(key) { | |
return new Promise((resolve, reject) => { | |
this._client.get(key, (err, reply) => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve(reply); | |
} | |
}); | |
}); | |
} | |
} | |
module.exports = RedisClient; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment