Last active
October 26, 2018 22:14
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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