|
| 1 | + |
| 2 | + |
| 3 | +# Cache API Key/Value store |
| 4 | + |
| 5 | +Fast and efficient key/value store with +50MB storage capacity in [most browsers](https://developer.mozilla.org/en-US/docs/Web/API/Cache#Browser_compatibility), expiration and JSON object data-type. |
| 6 | + |
| 7 | +It’s currently available in Chrome >= 40, Firefox >=39 and Opera >= 27. |
| 8 | + |
| 9 | +Safari and Edge recently introduced support for it. |
| 10 | + |
| 11 | +# Install |
| 12 | + |
| 13 | +``` |
| 14 | +npm install --save cache-api-keyval |
| 15 | +``` |
| 16 | + |
| 17 | +# Use |
| 18 | + |
| 19 | +```html |
| 20 | +<script src="/cache-api-keyval.js"></script> |
| 21 | +<script> |
| 22 | +
|
| 23 | +// load database |
| 24 | +var db = new CacheApiDB('my-store', { namespace: 'optional' }); |
| 25 | +
|
| 26 | +if (db.supported) { // Cache API supported by browser |
| 27 | +
|
| 28 | + // set JSON object data |
| 29 | + db.set('key', { json: 'object' }); |
| 30 | +
|
| 31 | + // set text data with expiration in 24 hours |
| 32 | + db.set('key2', 'string', 86400); |
| 33 | +
|
| 34 | + // get data from cache |
| 35 | + db.get('key').then(function(json) { |
| 36 | + console.log('json cache data', json); |
| 37 | + }); |
| 38 | +
|
| 39 | + // prune expired cache entries |
| 40 | + db.prune(); |
| 41 | +
|
| 42 | +} |
| 43 | +</script> |
| 44 | +``` |
| 45 | + |
| 46 | +## Fallback storage |
| 47 | + |
| 48 | +To enable a fallback storage for browsers that do not support Cache API, you can define a constructor on global variable `CacheApiDBFallback`. The constructor needs to provide 4 methods: `set`, `get`, `del` and `prune`. |
| 49 | + |
| 50 | +```js |
| 51 | +window.CacheApiDBFallback = function(store, options) { |
| 52 | + |
| 53 | + this.get = function(key) { /* return key from store */ } |
| 54 | + this.set = function(key,data,expire) { /* set key in store */ } |
| 55 | + this.det = function(key) { /* delete key from store */ } |
| 56 | + this.prune = function() { /* cleanup database */ } |
| 57 | +}; |
| 58 | +``` |
0 commit comments