A description of how to run an existing CouchApp on PouchDB in the browser using service workers - without any modifications to existing code being necessary! The best thing is that if service workers aren't available, the CouchApp will still run as normal: that is, online.
Only tested in Chromium currently, browser support for service workers is still rare. To learn more about this particular CouchApp (it's a simple website), see its design document in Futon.
First, rewrites.json
. Add a few endpoints so PouchDB can replicate from the db:
{
"from": "resources",
"to": "fake-root.json"
},
{
"from": "resources/db",
"to": "../.."
},
{
"from": "resources/db/*",
"to": "../../*"
},
_attachments/fake-root.json is just:
{"couchdb":"Welcome","uuid":"8e3e6d962d1833a6df7aca53aadfa857","version":"1.5.0","vendor":{"name":"Ubuntu","version":"14.04"}}
It shouldn't be necessary, but it is to trick PouchDB into replicating. Probably a (window.fetch()
-only) PouchDB bug, but it needs more research into it to be sure.
Then, the nice stuff. Including the service worker in the main template (templates/page.html
) is simple:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('{{ &base }}/workerbundle.js');
}
(&base is handled by the templating system used in this CouchApp)
The referred attachments/workerbundle.js
is a browserified version of the file worker.js
(see the next file in this Gist). While worker.js
isn't that big, part of it could be abstracted away into a library of its own, making this process easier.
That's all!
demo still available via: http://ma.rtendevri.es:5984/brassbandwirdum/_design/brassbandwirdum/_rewrite/