RedisCacheAdapter: add some additional checks and defaults (#2991)

This commit is contained in:
Tyler Brock
2016-11-02 15:13:55 -07:00
committed by GitHub
parent af700d7a4a
commit 801308d9b7

View File

@@ -1,7 +1,7 @@
import redis from 'redis';
import logger from '../../logger';
const DEFAULT_REDIS_TTL = 30 * 1000; // 30 seconds
const DEFAULT_REDIS_TTL = 30 * 1000; // 30 seconds in milliseconds
function debug() {
logger.debug.apply(logger, ['RedisCacheAdapter', ...arguments]);
@@ -30,17 +30,23 @@ export class RedisCacheAdapter {
return this.p;
}
put(key, value, ttl) {
put(key, value, ttl = DEFAULT_REDIS_TTL) {
value = JSON.stringify(value);
debug('put', key, value, ttl);
if (ttl === 0) {
return this.p; // ttl of zero is a logical no-op, but redis cannot set expire time of zero
}
if (ttl < 0 || isNaN(ttl)) {
ttl = DEFAULT_REDIS_TTL;
}
this.p = this.p.then(() => {
return new Promise((resolve, _) => {
if (ttl) {
this.client.psetex(key, ttl, value, function(err, res) {
if (ttl === Infinity) {
this.client.set(key, value, function(err, res) {
resolve();
});
} else {
this.client.set(key, value, function(err, res) {
this.client.psetex(key, ttl, value, function(err, res) {
resolve();
});
}