Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active October 26, 2018 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccnokes/81768dd1e03d29a895efe0363960b3e4 to your computer and use it in GitHub Desktop.
Save ccnokes/81768dd1e03d29a895efe0363960b3e4 to your computer and use it in GitHub Desktop.
Example of how you could use the Cache API to create a generic async key/value store. Something like this could be used over localStorage because it allows for more space and is available to workers. Working example: https://jsfiddle.net/ccnokes/790xaw53/
// Working example: https://jsfiddle.net/ccnokes/790xaw53/
class Storage {
constructor(key = location.origin + '/cache-key-v1') {
this.KEY = key;
}
get(id) {
return caches.open(this.KEY)
.then(cache => cache.match(id))
.then(res => {
if (res) {
return res.json();
} else {
return null;
}
});
}
set(id, val) {
return caches.open(this.KEY)
.then(cache => cache.put(id, new Response(JSON.stringify(val))));
}
delete(id) {
return caches.open(this.KEY)
.then(cache => cache.delete(id))
}
deleteAll() {
return caches.delete(this.KEY);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment