Skip to content

Commit a87094d

Browse files
committed
Request cacheability follow the spec
Relevant spec part: https://w3c.github.io/ServiceWorker/\#cache-addAll
1 parent 526ee36 commit a87094d

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

packages/service-worker-mock/__tests__/Cache.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,28 @@ describe('Cache', () => {
6363

6464
expect(keys.length).toBe(1);
6565
});
66+
67+
it('throw when the request is not cacheable', async () => {
68+
const cache = new Cache();
69+
[
70+
'HEAD',
71+
'POST',
72+
'PUT',
73+
'DELETE',
74+
'CONNECT',
75+
'OPTIONS',
76+
'TRACE',
77+
'PATCH'
78+
].forEach((method) => {
79+
cache.put(new Request('http://example.org', { method })).catch((e) => {
80+
expect(e).toEqual(new TypeError(`'${method}' HTTP method is unsupported.`));
81+
});
82+
});
83+
84+
expect(async () => {
85+
cache.put(new Request('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')).catch((e) => {
86+
expect(e).toEqual(new TypeError('Request scheme \'data\' is unsupported'));
87+
});
88+
});
89+
});
6690
});

packages/service-worker-mock/models/Cache.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,15 @@
11
// https://developer.mozilla.org/en-US/docs/Web/API/Cache
2+
function validateCacheableRequest(request) {
3+
const requestScheme = new URL(request.url).protocol.replace(':', '');
4+
if (request.method !== 'GET') {
5+
throw new TypeError(`'${request.method}' HTTP method is unsupported.`);
6+
}
7+
if (!['http', 'https'].includes(requestScheme)) {
8+
throw new TypeError(`Request scheme '${requestScheme}' is unsupported`);
9+
}
10+
return true;
11+
}
12+
213
class Cache {
314
constructor() {
415
this.store = new Map();
@@ -40,6 +51,12 @@ class Cache {
4051
request = new Request(request);
4152
// Add relative url as well (non-standard)
4253
this.store.set(relativeUrl, { request, response });
54+
} else {
55+
try {
56+
validateCacheableRequest(request);
57+
} catch (error) {
58+
return Promise.reject(error);
59+
}
4360
}
4461

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

0 commit comments

Comments
 (0)