Skip to content

Instantly share code, notes, and snippets.

@ithinkihaveacat
Last active March 7, 2017 17:06
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 ithinkihaveacat/748b5d611e6aa7dc4bee988a6af25b84 to your computer and use it in GitHub Desktop.
Save ithinkihaveacat/748b5d611e6aa7dc4bee988a6af25b84 to your computer and use it in GitHub Desktop.
"Globals" in service workers via the cache and Proxies
getGlobal('flags').then(flags => {
flags['debug'] = true;
flags['email'] = 'xxx@example.com';
});
// sometime later
getGlobal('flags').then(flags => {
console.log(JSON.stringify(flags)); // -> {"debug":true,"email":"xxx@example.com"}
});
function getGlobal(name) {
return caches.open('globals').then(cache => {
function put(obj) {
let req = new Request(name);
let res = new Response(JSON.stringify(obj));
return cache.put(req, res).then(() => obj);
}
return cache.match(new Request(name)).then(r => {
return r ? r.json() : put({});
}).then(obj => {
return new Proxy(obj, {
"set": (obj, k, v) => {
obj[k] = v;
put(obj);
return obj;
},
"deleteProperty": (obj, k) => {
delete obj[k];
put(obj);
return true;
}
});
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment