mirror of
https://github.com/TryGhost/Ghost.git
synced 2024-12-27 21:03:29 +03:00
f74b19ab61
refs https://github.com/TryGhost/Toolbox/issues/522 - The main feature of this cache wrapper is being able to "reset" the the cache without calling the "reset" on the wrapped cache. Being able to invalidate caches without accessing the data is a feature needed to run on caches with shared environment. - Cache invalidation happens through a special "reset time" key being added to each key when setting or getting a value, when the cache is reset the reset time is set to a new value - essentially invalidating all previously accessible values.
61 lines
1.9 KiB
JavaScript
61 lines
1.9 KiB
JavaScript
const assert = require('assert');
|
|
const InMemoryCache = require('@tryghost/adapter-cache-memory-ttl');
|
|
|
|
const EventAwareCacheWrapper = require('../index');
|
|
const {EventEmitter} = require('stream');
|
|
|
|
const sleep = ms => (
|
|
new Promise((resolve) => {
|
|
setTimeout(resolve, ms);
|
|
})
|
|
);
|
|
|
|
describe('EventAwareCacheWrapper', function () {
|
|
it('Can initialize', function () {
|
|
const cache = new InMemoryCache();
|
|
const wrappedCache = new EventAwareCacheWrapper({
|
|
cache
|
|
});
|
|
assert.ok(wrappedCache);
|
|
});
|
|
|
|
describe('get', function () {
|
|
it('calls a wrapped cache with extra key', async function () {
|
|
const cache = new InMemoryCache();
|
|
const lastReset = Date.now();
|
|
const wrapper = new EventAwareCacheWrapper({
|
|
cache: cache,
|
|
lastReset: lastReset
|
|
});
|
|
|
|
await wrapper.set('a', 'b');
|
|
assert.equal(await wrapper.get('a'), 'b');
|
|
assert.equal(await cache.get(`${lastReset}:a`), 'b');
|
|
});
|
|
});
|
|
|
|
describe('listens to reset events', function () {
|
|
it('resets the cache when reset event is triggered', async function () {
|
|
const cache = new InMemoryCache();
|
|
const lastReset = Date.now();
|
|
const eventRegistry = new EventEmitter();
|
|
const wrapper = new EventAwareCacheWrapper({
|
|
cache: cache,
|
|
lastReset: lastReset,
|
|
resetEvents: ['site.changed'],
|
|
eventRegistry: eventRegistry
|
|
});
|
|
|
|
await wrapper.set('a', 'b');
|
|
assert.equal(await wrapper.get('a'), 'b');
|
|
|
|
// let the time tick to get new lastReset
|
|
await sleep(100);
|
|
|
|
eventRegistry.emit('site.changed');
|
|
|
|
assert.equal(await wrapper.get('a'), undefined);
|
|
});
|
|
});
|
|
});
|