Skip to content

Commit

Permalink
Update CacheProvider to handle caches.open errors
Browse files Browse the repository at this point in the history
  • Loading branch information
gilbarbara committed Oct 16, 2023
1 parent fdc40a2 commit 7becdde
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 13 deletions.
22 changes: 15 additions & 7 deletions src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,24 @@ export default class CacheStore {

if (canUseDOM()) {
cacheName = window.REACT_INLINESVG_CACHE_NAME ?? CACHE_NAME;
usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE;
usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE && 'caches' in window;
}

if (usePersistentCache) {
caches.open(cacheName).then(cache => {
this.cacheApi = cache;
this.isReady = true;

this.subscribers.forEach(callback => callback());
});
caches
.open(cacheName)
.then(cache => {
this.cacheApi = cache;
this.isReady = true;

this.subscribers.forEach(callback => callback());
})
.catch(error => {
this.isReady = true;

// eslint-disable-next-line no-console
console.error(`Failed to open cache: ${error.message}`);
});
} else {
this.isReady = true;
}
Expand Down
31 changes: 25 additions & 6 deletions test/cache.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@ fetchMock.enableMocks();

const cacheMock = new CacheMock();

let cachesOpenPromise = new Promise(resolve => {
setTimeout(() => {
resolve(cacheMock);
}, 500);
});

Object.defineProperty(window, 'caches', {
value: {
...window.caches,
open: async () =>
new Promise(resolve => {
setTimeout(() => {
resolve(cacheMock);
}, 500);
}),
open: async () => cachesOpenPromise,
...cacheMock,
},
});
Expand Down Expand Up @@ -234,4 +235,22 @@ describe('CacheStore (external)', () => {
expect(cacheStore.isCached(jsUrl)).toBeFalse();
expect(fetchMock).toHaveBeenCalledTimes(1);
});

it('should handle caches.open errors', async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});

mockReady.mockClear();
cachesOpenPromise = Promise.reject(new Error('The operation is insecure.'));

const cacheStoreWithError = new CacheStore();

cacheStoreWithError.onReady(mockReady);

await waitFor(() => {
expect(consoleError).toHaveBeenCalledWith('Failed to open cache: The operation is insecure.');
});
expect(mockReady).not.toHaveBeenCalled();

consoleError.mockRestore();
});
});

0 comments on commit 7becdde

Please sign in to comment.