Skip to content

adding TTL option for redis cache adapter #3397

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Feb 27, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions spec/RedisCacheAdapter.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
var RedisCacheAdapter = require('../src/Adapters/Cache/RedisCacheAdapter').default;

describe('RedisCacheAdapter', function() {
var KEY = 'hello';
var VALUE = 'world';

function wait(sleep) {
return new Promise(function(resolve) {
setTimeout(resolve, sleep);
})
}

it('should get/set/clear', (done) => {
var cache = new RedisCacheAdapter({
ttl: NaN
});

cache.put(KEY, VALUE)
.then(() => cache.get(KEY))
.then((value) => expect(value).toEqual(VALUE))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what!@?! mind blown. I don't even understand how returning expect.... is "thenable", but super cool idiom. going to start using....

.then(() => cache.clear())
.then(() => cache.get(KEY))
.then((value) => expect(value).toEqual(null))
.then(done);
});

it('should expire after ttl', (done) => {
var cache = new RedisCacheAdapter(null, 1);

cache.put(KEY, VALUE)
.then(() => cache.get(KEY))
.then((value) => expect(value).toEqual(VALUE))
.then(wait.bind(null, 2))
.then(() => cache.get(KEY))
.then((value) => expect(value).toEqual(null))
.then(done);
});

it('should find un-expired records', (done) => {
var cache = new RedisCacheAdapter(null, 5);

cache.put(KEY, VALUE)
.then(() => cache.get(KEY))
.then((value) => expect(value).toEqual(VALUE))
.then(wait.bind(null, 1))
.then(() => cache.get(KEY))
.then((value) => expect(value).not.toEqual(null))
.then(done);
});
});
7 changes: 4 additions & 3 deletions src/Adapters/Cache/RedisCacheAdapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ function debug() {

export class RedisCacheAdapter {

constructor(ctx) {
this.client = redis.createClient(ctx);
constructor(redisCtx, ttl = DEFAULT_REDIS_TTL) {
this.client = redis.createClient(redisCtx);
this.p = Promise.resolve();
this.ttl = ttl;
}

get(key) {
Expand All @@ -30,7 +31,7 @@ export class RedisCacheAdapter {
return this.p;
}

put(key, value, ttl = DEFAULT_REDIS_TTL) {
put(key, value, ttl = this.ttl) {
value = JSON.stringify(value);
debug('put', key, value, ttl);
if (ttl === 0) {
Expand Down