Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@lukaszjanyga
Last active March 16, 2018 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukaszjanyga/91d581223ecefd4ed2744d9f0638c7ca to your computer and use it in GitHub Desktop.
Save lukaszjanyga/91d581223ecefd4ed2744d9f0638c7ca to your computer and use it in GitHub Desktop.
Simple redis cache
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;
}
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());
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