Storing SharePoint list data locally in IndexedDB with PouchDB and AngularJS

pouchdbPouchDB is an open-source JavaScript database inspired by Apache CouchDB that is designed to run well within the browser.

PouchDB was created to help web developers build applications that work as well offline as they do online. It enables applications to store data locally while offline, then synchronize it with CouchDB and compatible servers when the application is back online, keeping the user’s data in sync no matter where they next login.

The below code should give you a full life cycle of:

  1. Delete a DB if it exists
  2. Create a new DB
  3. Get SharePoint list data
  4. Add returned data to the IndexedDB
  5. Console out errors if issues are encountered.

 

var req = indexedDB.deleteDatabase(“demodata”);
req.onsuccess = function() {
    console.log(“Deleted database successfully”);
    // Create the client side DB
    var db = new PouchDB(‘demodata’);
    console.log(“DB created”);

    // Get info
    db.info().then(function (info) {
        console.log(info);
    });

    // BEGIN: Get list data
    $http({
        method: ‘GET’,
        url: _spPageContextInfo.webAbsoluteUrl + “/_api/web/lists/getByTitle(‘demolist’)/items”,
        cache: true,
        headers: {
            “Accept”: “application/json;odata=verbose”
        }
    }).success(function(data, status, headers, config) {
        var demodataValues = data.d.results;
        var demodata = {
            “_id”: “demo”,
            “demodataValues”: demodataValues
        };
        db.put(demodata);
        console.log(“Demo injected.”);
    }).error(function(data, status, headers, config) {

        console.log(“SP error”);

    });
    // END: Get list data
};
req.onerror = function() {
    console.log(“Couldn’t delete database”);
};
req.onblocked = function() {
    console.log(“Couldn’t delete database due to the operation being blocked”);
};