Last active
March 7, 2017 17:06
-
-
Save ithinkihaveacat/748b5d611e6aa7dc4bee988a6af25b84 to your computer and use it in GitHub Desktop.
"Globals" in service workers via the cache and Proxies
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
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"} | |
}); |
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
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