2021-12-23 05:47:47 +08:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
const Cache = require("../lib/Cache");
|
|
|
|
const { ItemCacheFacade, MultiItemCache } = require("../lib/CacheFacade");
|
|
|
|
|
|
|
|
describe("MultiItemCache", () => {
|
2025-07-02 20:10:54 +08:00
|
|
|
it("throws when getting items from an empty Cache", () => {
|
2021-12-23 05:47:47 +08:00
|
|
|
const multiItemCache = new MultiItemCache(generateItemCaches(0));
|
2025-07-17 00:13:14 +08:00
|
|
|
expect(() => multiItemCache.get((_) => _())).toThrow(/_ is not a function/);
|
2021-12-23 05:47:47 +08:00
|
|
|
});
|
|
|
|
|
2025-07-02 20:10:54 +08:00
|
|
|
it("returns the single ItemCacheFacade when passed an array of length 1", () => {
|
2021-12-23 05:47:47 +08:00
|
|
|
const itemCaches = generateItemCaches(1);
|
|
|
|
const multiItemCache = new MultiItemCache(itemCaches);
|
|
|
|
expect(multiItemCache).toBe(itemCaches[0]);
|
|
|
|
});
|
|
|
|
|
2025-07-02 20:10:54 +08:00
|
|
|
it("retrieves items from the underlying Cache when get is called", () => {
|
2021-12-23 05:47:47 +08:00
|
|
|
const itemCaches = generateItemCaches(10);
|
|
|
|
const multiItemCache = new MultiItemCache(itemCaches);
|
|
|
|
const callback = (err, res) => {
|
|
|
|
expect(err).toBeNull();
|
|
|
|
expect(res).toBeInstanceOf(Object);
|
|
|
|
};
|
|
|
|
for (let i = 0; i < 10; ++i) {
|
|
|
|
multiItemCache.get(callback);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2025-07-02 20:10:54 +08:00
|
|
|
it("can get() a large number of items without exhausting the stack", () => {
|
2021-12-23 05:47:47 +08:00
|
|
|
const itemCaches = generateItemCaches(10000, () => undefined);
|
|
|
|
const multiItemCache = new MultiItemCache(itemCaches);
|
|
|
|
let callbacks = 0;
|
|
|
|
const callback = (err, res) => {
|
2022-01-10 21:00:18 +08:00
|
|
|
expect(err).toBeNull();
|
2021-12-23 05:47:47 +08:00
|
|
|
expect(res).toBeUndefined();
|
|
|
|
++callbacks;
|
|
|
|
};
|
|
|
|
multiItemCache.get(callback);
|
2025-07-02 20:10:54 +08:00
|
|
|
expect(callbacks).toBe(1);
|
2021-12-23 05:47:47 +08:00
|
|
|
});
|
|
|
|
|
2025-04-22 20:42:33 +08:00
|
|
|
/**
|
|
|
|
* @param {number} howMany how many generation
|
|
|
|
* @param {() => EXPECTED_ANY=} dataGenerator data generator fn
|
|
|
|
* @returns {EXPECTED_ANY[]} cache facades
|
|
|
|
*/
|
2021-12-23 05:47:47 +08:00
|
|
|
function generateItemCaches(howMany, dataGenerator) {
|
|
|
|
const ret = [];
|
|
|
|
for (let i = 0; i < howMany; ++i) {
|
|
|
|
const name = `ItemCache${i}`;
|
|
|
|
const tag = `ItemTag${i}`;
|
2024-07-31 11:31:11 +08:00
|
|
|
const dataGen = dataGenerator || (() => ({ name: tag }));
|
2021-12-23 05:47:47 +08:00
|
|
|
const cache = new Cache();
|
|
|
|
cache.hooks.get.tapAsync(
|
|
|
|
"DataReturner",
|
|
|
|
(_identifier, _etag, _gotHandlers, callback) => {
|
|
|
|
callback(undefined, dataGen());
|
|
|
|
}
|
|
|
|
);
|
|
|
|
const itemCache = new ItemCacheFacade(cache, name, tag);
|
|
|
|
ret[i] = itemCache;
|
|
|
|
}
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
});
|