Skip to content

Commit

Permalink
feat: make the keyv object an emitter
Browse files Browse the repository at this point in the history
  • Loading branch information
Mateu Aguiló Bosch committed Jun 16, 2018
1 parent b14e96a commit 87c248d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/KeyvLru.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
import type { MapInterface } from '../flow/types/MapInterface';

const lru = require('tiny-lru');
const EventEmitter = require('events');

/**
* An adaptor from tiny-lru to a Map API.
*/
class KeyvLru implements MapInterface {
class KeyvLru extends EventEmitter implements MapInterface {
// @TODO: Type this in a less generic way.
cache: Object;

Expand All @@ -19,7 +20,16 @@ class KeyvLru implements MapInterface {
expire?: number,
} = { max: 500 }
) {
super();
this.cache = lru(options.max, options.notify, options.ttl, options.expire);
if (options.notify) {
// This seems like a weird construct, but this is because tiny-lru passes
// the execution of this.cache.onchange to process.nextTick. nextTick
// expects a function.
this.cache.onchange = (event, serializedCache) => () => {
this.emit('change', event, serializedCache);
};
}
}

clear(): void {
Expand Down
12 changes: 12 additions & 0 deletions src/KeyvLru.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,16 @@ describe('KeyvLru', () => {
expect(sut.cache).toHaveLength(0);
});
});
test('events', done => {
expect.assertions(2);
const sut = new KeyvLru({ max: 10, notify: true });
sut.on('change', (event, serializedCache) => {
expect(event).toBe('set');
expect(serializedCache).toBe(
'{"expire":0,"max":10,"notify":true,"ttl":0,"cache":{"foo":{"next":"","previous":"","value":{"bar":true}}},"expires":{},"first":"foo","last":"foo","length":1}'
);
done();
});
sut.set('foo', { bar: true });
});
});

0 comments on commit 87c248d

Please sign in to comment.