|
| 1 | +/** |
| 2 | + * Copyright 2015 Google Inc. All rights reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + * |
| 16 | + */ |
| 17 | + |
| 18 | +if (!Cache.prototype.addAll) { |
| 19 | + Cache.prototype.addAll = function addAll(requests) { |
| 20 | + var cache = this; |
| 21 | + |
| 22 | + // Since DOMExceptions are not constructable: |
| 23 | + function NetworkError(message) { |
| 24 | + this.name = 'NetworkError'; |
| 25 | + this.code = 19; |
| 26 | + this.message = message; |
| 27 | + } |
| 28 | + NetworkError.prototype = Object.create(Error.prototype); |
| 29 | + |
| 30 | + return Promise.resolve().then(function() { |
| 31 | + if (arguments.length < 1) throw new TypeError(); |
| 32 | + |
| 33 | + // Simulate sequence<(Request or USVString)> binding: |
| 34 | + var sequence = []; |
| 35 | + |
| 36 | + requests = requests.map(function(request) { |
| 37 | + if (request instanceof Request) { |
| 38 | + return request; |
| 39 | + } |
| 40 | + else { |
| 41 | + return String(request); // may throw TypeError |
| 42 | + } |
| 43 | + }); |
| 44 | + |
| 45 | + return Promise.all( |
| 46 | + requests.map(function(request) { |
| 47 | + if (typeof request === 'string') { |
| 48 | + request = new Request(request); |
| 49 | + } |
| 50 | + |
| 51 | + var scheme = new URL(request.url).protocol; |
| 52 | + |
| 53 | + if (scheme !== 'http:' && scheme !== 'https:') { |
| 54 | + throw new NetworkError("Invalid scheme"); |
| 55 | + } |
| 56 | + |
| 57 | + return fetch(request.clone()); |
| 58 | + }) |
| 59 | + ); |
| 60 | + }).then(function(responses) { |
| 61 | + // TODO: check that requests don't overwrite one another |
| 62 | + // (don't think this is possible to polyfill due to opaque responses) |
| 63 | + return Promise.all( |
| 64 | + responses.map(function(response, i) { |
| 65 | + return cache.put(requests[i], response); |
| 66 | + }) |
| 67 | + ); |
| 68 | + }).then(function() { |
| 69 | + return undefined; |
| 70 | + }); |
| 71 | + }; |
| 72 | +} |
0 commit comments