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

Cloudant Webinar: Offline-Enabled Apps with Pou...

Cloudant Webinar: Offline-Enabled Apps with PouchDB

Mobile web apps shouldn't stop working when there's no network connection. Offline-enabled apps built using PouchDB can provide a better, faster user experience while potentially reducing battery and bandwidth usage.

Learn how to use the HTML5 Offline Application Cache, PouchDB, IBM® Cloudant®, and Cordova/PhoneGap to develop fully-featured and cross-platform native apps, responsive mobile web apps, or high-fidelity prototypes that work just as well offline as they do online.

Watch a recording of the webinar:
https://cloudant.com/resources/webinars/offline-enabled-apps-with-pouchdb/

Bradley Holt

April 22, 2015
Tweet

More Decks by Bradley Holt

Other Decks in Programming

Transcript

  1. Image Credit: Lynn Camp Prong (Explored) by AllieKF, on Flickr

    4 Offline First! Because being offline shouldn't be an error condition.!
  2. The Eight Fallacies of Distributed Computing 1.  The network is

    reliable 2.  Latency is zero 3.  Bandwidth is infinite 4.  The network is secure 5.  Topology doesn't change 6.  There is one administrator 7.  Transport cost is zero 8.  The network is homogeneous 10 Credit: The Eight Fallacies of Distributed Computing by Peter Deutsch
  3. 11 Offline-first is the only way 
 to achieve a

    true, 100% 
 always-on user experience.* ! *assuming the device is reliable!
  4. Benefits of Offline First 12 •  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
  5. Offline Patterns & Anti-Patterns •  Don't return an error for

    no reason •  Do let users view cached/saved data •  Do synchronize data when connected 13
  6. Offline Patterns & Anti-Patterns •  Don't return an error for

    no reason •  Do let users view cached/saved data •  Do synchronize data when connected 13
  7. Offline Patterns & Anti-Patterns •  Don't return an error for

    no reason •  Do let users view cached/saved data •  Do synchronize data when connected 13
  8. Offline Patterns & Anti-Patterns •  Don't return an error for

    no reason •  Do let users view cached/saved data •  Do synchronize data when connected 13
  9. Use Cases and Building Blocks 14 HTML5 Offline Application Cache

    Cordova/ PhoneGap PouchDB Cloudant/ CouchDB Fully-featured, cross- platform native apps ✓ ✓ ✓ Responsive mobile web apps ✓ ✓ ✓ High-fidelity prototypes ✓ ✓ ✓
  10. IBM Cloudant •  Globally distributed data layer for web and

    mobile applications •  MongoDB-style queries •  Advanced geospatial capabilities •  Full text search indexing 15
  11. HTML5 Offline Application Cache •  Enables fully-functional offline web apps

    •  Stores files and assets for offline browsing •  Makes page loads very fast, even when online 16 Image Credits: W3C HTML5 Logo
  12. Cache Manifest File 17 <html manifest="example.appcache">
 …
 </html>
 CACHE MANIFEST


    # v1 - 2015-01-08
 index.html
 logo.png
 app.css
 app.js
  13. PouchDB •  A database in your web browser •  Can

    synchronize with any database that implements the CouchDB Replication Protocol •  Makes create, read, update and delete operations extremely fast 19
  14. JSON Documents 20 {
 _id: "6EF9D2B0-13D3-1378-8D30-39E3CE0B36C2",
 _rev: "1-0b457efcf82fb29492ef927ba5b6ee15",
 type: "Feature",


    geometry: {
 type: "Point",
 coordinates: [
 -71.1028,
 42.3691
 ]
 },
 properties: {
 session_id: "3486b13f-7b8a-8a96-dfbf-9b82800e367f",
 timestamp: 1422928591717
 }
 }
  15. CouchDB Replication Protocol •  One-off, one way operation •  Peer-to-peer

    (masterless) •  Incremental •  Conflict detection 22
  16. Installing PouchDB 23 <script src=
 "https://cdn.jsdelivr.net/pouchdb/3.4.0/pouchdb.min.js"
 ></script>
 CACHE MANIFEST
 #

    v2 - 2015-01-08
 index.html
 logo.png
 app.css
 app.js
 https://cdn.jsdelivr.net/pouchdb/3.4.0/pouchdb.min.js
  17. PouchDB Code Examples 24 •  Creating a local PouchDB database

    •  Creating a new document •  Updating a document •  Deleting a document •  Querying a database •  Replicating PouchDB
  18. Creating a New Document 26 var db = new PouchDB("smart-meter");

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

    = new PouchDB("smart-meter"); db.put({
 _id: "2014-11-12T23:27:03.794Z",
 kilowatt_hours: 14
 });
  20. Updating a Document 28 // 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);
 });
  21. Deleting a Document 29 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);
 });
 });
  22. Querying a Database with allDocs" 31 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);
 });
  23. allDocs Options •  include_docs" •  conflicts" •  attachments" •  startkey"

    •  endkey" •  inclusive_end (true by default) •  limit" •  skip" •  descending" •  key" •  keys" 32
  24. Querying a Database with Map/Reduce 33 •  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"
  25. Querying a Database with PouchDB Find •  Based on Cloudant

    Query (Mango) •  MongoDB-style query language •  Define fields to index 34 Image Credit: Mango with section on a white background by bangdoll, on Flickr
  26. Replicating PouchDB 35 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
 });
  27. Cross-Origin Resource Sharing (CORS) •  Enable Cross-Origin Resource Sharing (CORS)

    on remote database •  Browsers place security restrictions on cross-site HTTP requests •  If you run into a problem, remember this warning! 36 Image Credit: Grunge Warning Sign - Do Not Read This Sign by Nicolas Raymond, on Flickr
  28. Bidirectional Replication 37 var db = new PouchDB("smart-meter");
 var remoteDb

    = new PouchDB(
 "https://bradley-holt.cloudant.com/smart-meter"
 );
 
 db.sync(remoteDB);
  29. Live Replication 38 var db = new PouchDB("smart-meter");
 var remoteDb

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

    {
 // A document has been created, updated, or deleted
 }).on("error", function (err) {
 // An error has occurred
 });
  31. Location Tracker •  Stores data locally in PouchDB •  Front

    end built with AngularJS •  Authentication logic built with Node.js •  User interface built with Leaflet •  Replicates location data to Cloudant •  More info: https://cloudant.com/location-tracker/ 41
  32. Image Credits 42 •  Device landscape by Jeremy Keith, on

    Flickr <https://www.flickr.com/photos/adactio/6153481666> •  Lynn Camp Prong (Explored) by AllieKF, on Flickr <https://www.flickr.com/photos/allie_k/14501117120> •  W3C HTML5 Logo <http://www.w3.org/html/logo/> •  build.phonegap by Andrés Álvarez Iglesias, on Flickr <https://www.flickr.com/photos/doctorserone/5682929553> •  Mango with section on a white background by bangdoll, on Flickr <https://www.flickr.com/photos/bangdoll/5665235102> •  Grunge Warning Sign - Do Not Read This Sign by Nicolas Raymond, on Flickr <https://www.flickr.com/photos/80497449@N04/7417352980>