Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions packages/service-worker-mock/__tests__/Cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,28 @@ describe('Cache', () => {

expect(keys.length).toBe(1);
});

it('throw when the request is not cacheable', async () => {
const cache = new Cache();
[
'HEAD',
'POST',
'PUT',
'DELETE',
'CONNECT',
'OPTIONS',
'TRACE',
'PATCH'
].forEach((method) => {
cache.put(new Request('http://example.org', { method })).catch((e) => {
expect(e).toEqual(new TypeError(`'${method}' HTTP method is unsupported.`));
});
});

expect(async () => {
cache.put(new Request('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')).catch((e) => {
expect(e).toEqual(new TypeError('Request scheme \'data\' is unsupported'));
});
});
});
});
16 changes: 16 additions & 0 deletions packages/service-worker-mock/models/Cache.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
// https://developer.mozilla.org/en-US/docs/Web/API/Cache
function validateCacheableRequest(request) {
const requestScheme = new URL(request.url).protocol.replace(':', '');
if (request.method !== 'GET') {
throw new TypeError(`'${request.method}' HTTP method is unsupported.`);
}
if (!['http', 'https'].includes(requestScheme)) {
throw new TypeError(`Request scheme '${requestScheme}' is unsupported`);
}
}

class Cache {
constructor() {
this.store = new Map();
Expand Down Expand Up @@ -40,6 +50,12 @@ class Cache {
request = new Request(request);
// Add relative url as well (non-standard)
this.store.set(relativeUrl, { request, response });
} else {
try {
validateCacheableRequest(request);
} catch (error) {
return Promise.reject(error);
}
}

this.store.set(request.url, { request, response });
Expand Down