Dale Harvey: PouchDB

Orde Saunders' avatarPublished: by Orde Saunders

Dale Harvey (@daleharvey) was speaking at Glasgow.js about PouchDB - a JavaScript library that allows you to store and query data for web applications that need to work offline, and sync with an online database when you are online, these are my notes from his talk.

What is PouchDB

Reimplementation of CouchDB inside the browser.  Couch does master-to-master sync, even works with offline data.  People have lots of devices and they are often not connected - applications should work offline.  Being web based it is available on all platforms.  Works on browser storage APIs (IndexDB and WebSQL), there is a version being worked on for Node.  TouchDB library is available for iOS and Android native apps.

Browser restrictions

As Pouch runs in the browser it is bound by the same restrictions as normal JavaScript

  • Cross origin policy restricts communication - use CORS
  • Can't work from file:// URLs - run a webserver (python -m SimpleHTTPServer)

Working with Pouch

Pouch is a client for Couch HTTP server.

  • idb:// goes to local
  • http:// goes remote (Couch)

Transport does not have to be http - could be sockets.

Code is written in Node idioms, uses callbacks.

Fields starting with _ are special.

Changes feed

Every time a record changes it is in the changes feed which can handle events e.g. to update UI.  This is also how master replication is handled.

Replicate

Replicate  handles syncing with remote, setting to continuous true will keep them in sync in future.  As long as the app is running it can sync.  HTML5 browser events for offline/ online can be used to trigger syncing.  Additions, edits and deletions are synced.

When you edit a record in you tag it with a revision.  If there is a revision mis-match between your edit and the stored version then there is a conflict.  Conflicts are flagged and conflicting versions are available.  All future updates are added to conflicts until resolved.  Resolution can be achieved according to rules defined in the application and then when marked as resolved it will replicate out.

PouchDB, TouchDB and CouchDB can all sync seamlessly.  PouchDB can sync between two instances of itself in the same browser context and then back to the server.

There's no discovery built in - this has to be handled by the app.  This is suitable for cloud sync to a dedicated server, peer to peer is going to be interesting.


Comments, suggestions, corrections? Contact me via this website