0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-02-03 23:00:14 -05:00

Added async cache support to Tags repository

refs https://github.com/TryGhost/Toolbox/issues/515

- The caches relying on external storage like e.g.: Redis, the get/set operations are usually async. The tags repository should be working with these as caching is expected to be non-in-memory for these data.
This commit is contained in:
Naz 2023-02-13 14:02:59 +08:00 committed by naz
parent 9d4ea7b8c9
commit 1c12d789f9
2 changed files with 37 additions and 4 deletions

View file

@ -40,11 +40,15 @@ module.exports = class TagsPublicRepository {
.filter(option => (option !== 'context'));
const optionsForCacheKey = _.pick(options, permittedOptions);
// TODO: filter options, for example do we care make a distinction about
// logged in member on the tags level?
// NOTE: can be more aggressive here with filtering options,
// for example, do we care make a distinction for logged
// in member on the tags level?
cacheKey = `get-all-${JSON.stringify(optionsForCacheKey)}`;
const cachedResult = this.#cache.get(cacheKey);
const cachedResult = await this.#cache.get(cacheKey);
// NOTE: if the cache result is empty still going to the DB
// this check can be removed if we want to be more aggressive
// with caching and avoid and extra DB call
if (cachedResult) {
return cachedResult;
}
@ -53,7 +57,7 @@ module.exports = class TagsPublicRepository {
const dbResult = await this.#getAllDB(options);
if (this.#cache) {
this.#cache.set(cacheKey, dbResult);
await this.#cache.set(cacheKey, dbResult);
}
return dbResult;

View file

@ -100,5 +100,34 @@ describe('TagsPublicRepository', function () {
assert.equal(tagStub.findPage.callCount, 2, 'should be called every time the item is not in the cache');
assert.ok(tagStub.findPage.calledWith({limit: 'all'}));
});
it('works with a cache that has an asynchronous interface', async function () {
const tagStub = {
findPage: sinon.stub().resolves({
data: [{
get(key) {
return key;
}
}],
meta: {}
}),
permittedOptions: sinon.stub().returns(['limit'])
};
const asyncMemoryCache = {
get: sinon.stub().resolves('test'),
set: sinon.stub().resolves()
};
const repo = new TagsPublicRepository({
Tag: tagStub,
cache: asyncMemoryCache
});
const result = await repo.getAll();
assert.ok(asyncMemoryCache.get.calledOnce);
assert.equal('test', result, 'should return the value from the cache');
});
});
});