1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // A simple, incomplete implementation of the CacheStorage API, intended to facilitate
6 // end to end serviceworker testing.
8 // See https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#cache-storage
11 var CacheStorage = function() {
12 this.cachesByName = {};
15 CacheStorage.prototype.get = function(key) {
16 if (this.cachesByName.hasOwnProperty(key)) {
17 return Promise.resolve(this.cachesByName[key]);
19 return Promise.reject('not found');
22 CacheStorage.prototype.has = function(key) {
23 return Promise.resolve(this.cachesByName.hasOwnProperty(key));
26 // FIXME: Engage standardization on removing this method from the spec.
27 CacheStorage.prototype.set = Promise.reject.bind(Promise, 'CacheStorage.prototype.set() not implemented.');
29 // FIXME: Engage standardization on adding this method to the spec.
30 CacheStorage.prototype.create = function(key) {
31 this.cachesByName[key] = new Cache();
33 return Promise.resolve();
36 // FIXME: Engage standarization on adding this method to the spec.
37 CacheStorage.prototype.rename = function(fromKey, toKey) {
38 if (!this.cachesByName.hasOwnProperty(fromKey)) {
39 return Promise.reject('not found');
41 this.cachesByName[toKey] = this.cachesByName[fromKey];
42 delete this.cachesByName[fromKey];
44 return Promise.resolve();
47 CacheStorage.prototype.clear = function() {
48 this.cachesByName = {};
50 return Promise.resolve();
53 CacheStorage.prototype.delete = function(key) {
54 delete this.cachesByName[key];
56 return Promise.resolve();
59 CacheStorage.prototype.forEach = function(callback, thisArg) {
60 Object.keys(this.cachesByName).map(function(key) {
61 thisArg.callback(this.cachesByName[key], key, this);
63 return Promise.resolve();
66 // FIXME: Implement this.
67 CacheStorage.prototype.entries = Promise.reject.bind(Promise, 'CacheStorage.prototype.entries() not implemented.');
69 CacheStorage.prototype.keys = function() {
70 return Promise.resolve(Object.keys(this.cachesByName));
73 CacheStorage.prototype.values = function() {
74 return Promise.resolve(Object.keys(this.cachesByName).map(function(key) {
75 return this.cachesByName[key];
79 CacheStorage.prototype.size = function() {
80 return Promise.resolve(Object.keys(this.cachesByName).length);
83 // FIXME: Figure out what should be done with undefined or poorly defined |cacheName| values.
84 CacheStorage.prototype.match = function(url, cacheName) {
85 return this.get(cacheName).then(function(cache) {
86 return cache.match(url);
90 global.caches = global.caches || new CacheStorage();
91 }(self)); // window or worker global scope.