Skip to content

Commit

Permalink
fix: re populate higher priority caches when a key is found in lower …
Browse files Browse the repository at this point in the history
…ones
  • Loading branch information
zzau13 committed Nov 2, 2022
1 parent e1e7e8b commit 7a6a10c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 6 deletions.
17 changes: 14 additions & 3 deletions src/multi-caching.ts
Expand Up @@ -25,12 +25,23 @@ export function multiCaching<Caches extends Cache[]>(
del: async (key) => {
await Promise.all(caches.map((cache) => cache.del(key)));
},
async wrap<T>(key: string, fn: () => Promise<T>): Promise<T> {
const value = await get<T>(key);
async wrap<T>(key: string, fn: () => Promise<T>, ttl?: Ttl): Promise<T> {
let value: T | undefined;
let i = 0;
for (; i < caches.length; i++) {
try {
value = await caches[i].get<T>(key);
if (value !== undefined) break;
} catch (e) {}
}
if (value === undefined) {
const result = await fn();
await set<T>(key, result);
await set<T>(key, result, ttl);
return result;
} else {
for (let j = 0; j < i; j++) {
await caches[j].set(key, value, ttl);
}
}
return value;
},
Expand Down
31 changes: 28 additions & 3 deletions test/multi-caching.test.ts
@@ -1,4 +1,8 @@
import { describe, expect, it, beforeEach } from 'vitest';
import { faker } from '@faker-js/faker';

import { sleep } from './utils';

import {
Cache,
caching,
Expand All @@ -7,9 +11,8 @@ import {
multiCaching,
Store,
} from '../src';
import { faker } from '@faker-js/faker';

describe('multiCaching', function () {
describe('multiCaching', () => {
let memoryCache: MemoryCache;
let memoryCache2: MemoryCache;
let memoryCache3: MemoryCache;
Expand Down Expand Up @@ -38,7 +41,7 @@ describe('multiCaching', function () {
describe('get(), set(), del(), reset(), mget(), mset()', () => {
let value: string;

beforeEach(function () {
beforeEach(() => {
multiCache = multiCaching([memoryCache, memoryCache2, memoryCache3]);
key = faker.datatype.string(20);
value = faker.datatype.string();
Expand Down Expand Up @@ -136,4 +139,26 @@ describe('multiCaching', function () {
});
});
});

describe('issues', () => {
it('#253', async () => {
const cache0 = await caching('memory', { ttl: 100 });
const cache1 = await caching('memory', { ttl: 1000 });
const multi = multiCaching([cache0, cache1]);
const key = 'bar';
const value = 'foo';

const fn = async () => value;

await multi.wrap(key, fn);
await sleep(100);
await expect(cache0.get(key)).resolves.toBeUndefined();
await expect(cache1.get(key)).resolves.toEqual(value);

await multi.wrap(key, fn);

await expect(cache0.get(key)).resolves.toEqual(value);
await expect(cache1.get(key)).resolves.toEqual(value);
});
});
});

0 comments on commit 7a6a10c

Please sign in to comment.