Skip to content

Commit

Permalink
Merge pull request #78 from camptocamp/clear-cache
Browse files Browse the repository at this point in the history
Adds a clearCache function
  • Loading branch information
jahow authored Oct 25, 2024
2 parents ec1e4fe + 37ad5bc commit 4f311f2
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export type {
} from './shared/models.js';
export { default as OgcApiEndpoint } from './ogc-api/endpoint.js';
export * from './ogc-api/model.js';
export { useCache } from './shared/cache.js';
export { useCache, clearCache } from './shared/cache.js';
export {
sharedFetch,
setFetchOptions,
Expand Down
18 changes: 16 additions & 2 deletions src/shared/cache.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import {
_resetCache,
clearCache,
getCache,
purgeEntries,
purgeOutdatedEntries,
readCacheEntry,
setCacheExpiryDuration,
storeCacheEntry,
Expand All @@ -22,7 +23,7 @@ describe('cache utils', () => {
beforeEach(async () => {
// clear all cache entries
NOW = 50000;
await purgeEntries();
await purgeOutdatedEntries();
// set start time
NOW = 10000;
});
Expand Down Expand Up @@ -108,6 +109,19 @@ describe('cache utils', () => {
});
});
});
describe('clearCache', () => {
let result;
beforeEach(async () => {
await storeCacheEntry({ old: true }, 'test', 'entry', '03');
NOW = 10800;
await clearCache();
result = await useCache(factory, 'test', 'entry', '03');
});
it('do not use the cached function object', () => {
expect(factory).toHaveBeenCalled();
expect(result).toEqual({ fresh: true });
});
});
});

describe('when the Cache API is not available', () => {
Expand Down
16 changes: 14 additions & 2 deletions src/shared/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export async function useCache<T>(
factory: () => T | Promise<T>,
...keys: string[]
): Promise<T> {
await purgeEntries();
await purgeOutdatedEntries();
if (await hasValidCacheEntry(...keys)) {
return readCacheEntry(...keys);
}
Expand All @@ -118,7 +118,7 @@ export async function useCache<T>(
/**
* Removes all expired entries from the cache
*/
export async function purgeEntries() {
export async function purgeOutdatedEntries() {
const cache = await getCache();
if (!cache) return;
const keys = await cache.keys();
Expand All @@ -128,3 +128,15 @@ export async function purgeEntries() {
await cache.delete(key);
}
}

/**
* Remove all cache entries; will not prevent the creation of new ones
*/
export async function clearCache() {
const cache = await getCache();
if (!cache) return;
const keys = await cache.keys();
for (const key of keys) {
await cache.delete(key);
}
}

0 comments on commit 4f311f2

Please sign in to comment.