Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Build Offline-Enabled Apps with PouchDB at Code...

Build Offline-Enabled Apps with PouchDB at CodeMash 2015

Mobile web apps shouldn't stop working when there's no network connection. Learn how to build cross-platform mobile web apps that work just as well offline as they do online. This talk will demonstrate how you can use HTML5 and PouchDB, an open source syncing JavaScript database that runs within a web browser, to provide a better, faster user experience, both offline and online. Learn how PouchDB synchronization can be used to replicate to and from a remote database, such as CouchDB or IBM Cloudant (a globally distributed data layer for web and mobile applications), whenever an Internet connection is available.

Bradley Holt

January 08, 2015
Tweet

More Decks by Bradley Holt

Other Decks in Programming

Transcript

  1. Build Offline-Enabled Apps with PouchDB CodeMash Thursday, January 8, 2015

    Bradley Holt <[email protected]> Developer Advocate, IBM Cloudant @BradleyHolt
  2. Offline First 2 •  Better, faster user experience, both offline

    and online •  Allow your users to work offline or with limited connectivity •  Potentially saves battery life and bandwidth usage © 2014 IBM Corporation
  3. Building Blocks 3 •  HTML5 Offline Application Cache •  PouchDB

    •  IBM Cloudant •  Cordova/PhoneGap © 2014 IBM Corporation
  4. Use Cases 4 •  Fully-featured, cross-platform native apps •  Responsive

    mobile web apps •  High-fidelity prototypes © 2014 IBM Corporation
  5. Cache Manifest File 6 <html manifest="example.appcache">
 …
 </html>
 CACHE MANIFEST


    # v1 - 2015-01-08
 index.html
 logo.png
 app.css
 app.js © 2014 IBM Corporation
  6. PouchDB: A Database in Your Web Browser 7 Image Credits:

    Website address / URL bar by Descrier, on Flickr; database by Tim Morgan, on Flickr © 2014 IBM Corporation
  7. JSON Documents 8 {
 "_id": "1764AA5F-6F88-9414-A633-7202B20CE5C7",
 "_rev": "1-4c0aed6544150aa643565a0893e1ce01",
 "meter": "0123456789",


    "interval_start": 1416182400,
 "interval_end": 1416247200,
 "kilowatt_hours": 14
 } © 2014 IBM Corporation
  8. PouchDB Replication 9 Image Credit: database by Tim Morgan, on

    Flickr Local Remote © 2014 IBM Corporation
  9. PouchDB Replication 10 •  Implements the CouchDB Replication Protocol: • 

    one-off, one way operation •  peer-to-peer •  incremental •  conflict detection © 2014 IBM Corporation
  10. Installing PouchDB 11 <script src=
 "//cdn.jsdelivr.net/pouchdb/3.2.1/pouchdb.min.js"
 ></script>
 CACHE MANIFEST
 #

    v2 - 2015-01-08
 index.html
 logo.png
 app.css
 app.js
 //cdn.jsdelivr.net/pouchdb/3.1.0/pouchdb.min.js " © 2014 IBM Corporation
  11. IBM Cloudant •  Globally distributed data layer for web and

    mobile applications •  MongoDB-style queries •  Advanced geospatial capabilities •  Full text search indexing 12 © 2014 IBM Corporation
  12. Apache Cordova and PhoneGap 13 Image Credit: build.phonegap by Andrés

    Álvarez Iglesias, on Flickr © 2014 IBM Corporation
  13. PouchDB Code Examples 14 •  Creating a local PouchDB database

    •  Creating a new document •  Updating a document •  Deleting a document •  Querying a database •  Replicating PouchDB © 2014 IBM Corporation
  14. Creating a Local PouchDB Database 15 var db = new

    PouchDB("smart-meter"); © 2014 IBM Corporation
  15. Creating a New Document 16 var db = new PouchDB("smart-meter");

    
 db.post({
 date: "2014-11-12T23:27:03.794Z",
 kilowatt_hours: 14
 }); © 2014 IBM Corporation
  16. Creating a New Document, Specifying its ID 17 var db

    = new PouchDB("smart-meter"); db.put({
 _id: "2014-11-12T23:27:03.794Z",
 kilowatt_hours: 14
 }); © 2014 IBM Corporation
  17. Updating a Document 18 // Get the document
 db.get("2014-11-12T23:27:03.794Z").then(function (doc)

    {
 // Update the value for kilowatt hours
 doc.kilowatt_hours = 15;
 // Put the document back to the database
 return db.put(doc);
 }).then(function () {
 // Get the document again
 return db.get("2014-11-12T23:27:03.794Z");
 }).then(function (doc) {
 console.log(doc);
 }); © 2014 IBM Corporation
  18. Deleting a Document 19 db.put({
 _id: "2014-11-12T23:27:03.794Z",
 kilowatt_hours: 14
 }).then(function

    () {
 // Get the document
 db.get("2014-11-12T23:27:03.794Z").then(function (doc) {
 // Remove the document from the database
 return db.remove(doc);
 }).then(function () {
 // Try to get the document again
 return db.get("2014-11-12T23:27:03.794Z");
 }).then(function (doc) {
 console.log(doc);
 }).catch(function (err) {
 console.log(err);
 });
 }); © 2014 IBM Corporation
  19. Deleting a Document 20 {
 message: "deleted",
 status: 404,
 name:

    "not_found”,
 error: true
 } © 2014 IBM Corporation
  20. Querying a Database with allDocs" 21 db.bulkDocs([
 {_id: "2014-11-12T23:27:03.794Z", kilowatt_hours:

    14},
 {_id: "2014-11-13T00:52:01.471Z", kilowatt_hours: 15},
 {_id: "2014-11-13T01:39:28.911Z", kilowatt_hours: 16},
 {_id: "2014-11-13T02:52:01.471Z", kilowatt_hours: 17}
 ]).then(function () {
 // Get all documents
 return db.allDocs({include_docs: true});
 }).then(function (response) {
 console.log(response);
 }).catch(function (err) {
 console.log(err);
 }); © 2014 IBM Corporation
  21. allDocs Options •  include_docs" •  conflicts" •  attachments" •  startkey"

    •  endkey" •  inclusive_end (true by default) •  limit" •  skip" •  descending" •  key" •  keys" 22 © 2014 IBM Corporation
  22. Querying a Database with Map/Reduce 23 •  Most queries can

    be done with allDocs (in PouchDB)" •  Map functions transform documents into indexes •  Reduce functions aggregate results of Map functions •  _sum" •  _count" •  _stats" © 2014 IBM Corporation
  23. Replicating PouchDB 24 var db = new PouchDB("smart-meter");
 var remoteDb

    = new PouchDB(
 "https://bradley-holt.cloudant.com/smart-meter"
 );
 
 db.replicate.to(remoteDb).on("complete", function () {
 // Replication has finished
 }).on('error', function (err) {
 // There was an error with replication
 }); © 2014 IBM Corporation
  24. Cross-Origin Resource Sharing (CORS) 25 © 2014 IBM Corporation Photo

    Credit: Grunge Warning Sign - Do Not Read This Sign by Nicolas Raymond, on Flickr
  25. Bidirectional Replication 26 var db = new PouchDB("smart-meter");
 var remoteDb

    = new PouchDB(
 "https://bradley-holt.cloudant.com/smart-meter"
 );
 
 db.sync(remoteDB); © 2014 IBM Corporation
  26. Live Replication 27 var db = new PouchDB("smart-meter");
 var remoteDb

    = new PouchDB(
 "https://bradley-holt.cloudant.com/smart-meter"
 );
 
 db.sync(remoteDB, {live: true}); © 2014 IBM Corporation
  27. Listening for Changes 28 db.changes({
 since: "now"
 }).on("change", function (change)

    {
 // A document has been created, updated, or deleted
 }).on("error", function (err) {
 // An error has occurred
 }); © 2014 IBM Corporation
  28. Remote Database Options 30 •  IBM Cloudant •  CouchDB • 

    PouchDB Server •  Anything that implements the CouchDB Replication Protocol © 2014 IBM Corporation
  29. IBM Cloudant 31 •  Sign up at cloudant.com •  Metered

    pricing for multi-tenant accounts •  No charge if your monthly usage is under $50 •  Fully-managed, high-performance dedicated clusters available © 2014 IBM Corporation
  30. CouchDB or PouchDB Server 32 Installing and Running CouchDB via

    Apt (Debian & Ubuntu):" $ sudo apt-get install couchdb
 $ couchdb
 
 
 Installing and Running CouchDB via Homebrew (Mac OS X):" $ brew install couchdb
 $ couchdb
 
 
 Installing and Running PouchDB Server via npm:" $ npm install -g pouchdb-server
 $ pouchdb-server --port 5984 © 2014 IBM Corporation
  31. IBM Cloudant Apache CouchDB •  Major contributions from IBM Cloudant

    to Apache CouchDB include: •  Clustering for horizontal scaling •  MongoDB inspired query language (Mango) •  Several CouchDB committers work for IBM Cloudant "IBM has a strong track record in open source software and a productive relationship with Apache; in fact, IBM was instrumental in bringing CouchDB to the [Apache Software Foundation] many years ago. IBM is fully supportive of our efforts here, and I’m looking forward to bringing increased resources to bear in support of the project." –Adam Kocoloski, Co-Founder and CTO of Cloudant 33 Cloudant and IBM: Our Commitment to Apache CouchDB © 2014 IBM Corporation