IndexedDB – Concept Simplified.

Greetings All! In my previous post I had blogged about Working with IndexedDB, but then I had only scratched the surface, so now lets dive in IndexedDB concept !

So first things first, IndexedDB as the name suggests uses indices to store and retrieve objects in a database. It is an API for storage of structured data at the the client side. IndexedDB provides separate API’s for Asynchronous access and Synchronous access.

The Synchronous API is intended for use only inside Web Workers. and has not yet been implemented by the major browsers. The Asynchronous API is the one that is normally used. You must also know that IIndexedDB is an alternative to WebSQL Database, which the W3C has deprecated.

So moving further, A Database may contain one or more uniquely named Object Stores. Now an Object Store is the one that stores the records in key-value pairs.

I have authored a code snippet while working on the Mozilla Student Project that I have taken up, that makes use of IndexedDB.

The documentation in the code will help you to understand how the code works.

 

</div>
<div>
<pre>/**
 * IndexedDB has been used for storage, retrieval and deletion of Documents from database.
 *
 * Database Details:
 *
 * Database :  documents
 * ObjectStore : doc
 *
 * Each entry is an object with fields timeStamp (number, which serves as key), filename (string, the document name),
 * text (string, the contents of the document, generally in html).
 *
 * Structure of Database Used:
 *		      Key Path : timeStamp
 *		      Field (text) : Document Name
 * 		      Field (text) : Document Contents [Generally in HTML]
 *
 */
var db;
const DB_NAME = "documents";

/**
 *Checks browser compatibilty with indexedDB and calls |initIndexedDB()|
 */
function init() {
  window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB;
  if (!window.indexedDB) {
    window.alert("Your browser doesn't support a stable version of IndexedDB. Saving and Loading Documents feature will not be available.");
  } else {
    initIndexedDB();
  }
};

/**
 *Creates or opens database.
 *Calls |displayDocList()| to display the list of documents in the database.
 */
function initIndexedDB() {
  var request = window.indexedDB.open(DB_NAME);

  request.onerror = function onError_Init(event) {
    alert("Error Opening/Creating Database");
  }

  request.onsuccess = function onSuccess_Init(event) {
    db = request.result;
    displayDocList();
  }

  request.onupgradeneeded = function onUpgradeNeeded(event) {
    db = event.target.result;
    var objectStore = db.createObjectStore("doc", {
      keyPath: "timeStamp"
    });
  }
};

/**
 *Saves the document in the database.
 *	@param	docName
 *	        Name of the Document
 *	@param	docContent
 *	        Content of the Document.
 *
 */
function saveDocument(docName, docContent) {
  var trans = db.transaction(["doc"], "readwrite");
  var store = trans.objectStore("doc");
  var data = {
    "filename": docName,
    "text": docContent,
    "timeStamp": Date.now()
  };
  var request = store.put(data);
  request.onsuccess = function onSuccess_Save(e) {
    displayDocList();
  };
  request.onerror = function onError_Save(e) {
    alert("An Error Occured while Saving Document!");
  };
};

/**
 *Deletes the document from the database.
 *	@param	id
 *	        timeStamp of the document that needs to be deleted
 */
function deleteDoc(id) {
  var trans = db.transaction(["doc"], "readwrite");
  var store = trans.objectStore("doc");
  var request = store.delete(id);
  request.onsuccess = function onSuccess_Del(e) {
    displayDocList();
  };

  request.onerror = function onError_Del(e) {
    alert("Delete Request Error !");
  };
};

/**
 *Displays the list of document present in the database.
 */
function displayDocList() {
  var listElement = document.getElementById("docList");
  listElement.innerHTML = "";

  var trans = db.transaction(["doc"], "readwrite");
  var store = trans.objectStore("doc");

  var cursorRequest = store.openCursor();
  cursorRequest.onsuccess = function onSuccess_Cursor(e) {
    var result = e.target.result;
    if ( !! result == false) return;
    renderDocNames(result.value);
    result.continue ();
  };

  cursorRequest.onerror = function onError_Cursor(e) {
    alert("Cursor Request Error !");
  }
};

/**
 *Captures the user input values of Document Name and Document Contents from Web page.
 *Calls |saveDocument()| method.
 */
function saveDoc() {
  var docName = document.getElementById('docName').value;
  var docContent = document.getElementsByTagName('section')[0].innerHTML;
  saveDocument(docName, docContent);
  document.getElementById('docName').value = "";
};
You can see this code in action at: http://abhishekp91.github.com/richtextdoc_edit_OWA/
where IndexedDB has been used to save and load Documents.
Thats all folks! Hope that was useful to you. Feel free to drop a comment if you like it or to even dislike it 😛 (do make suggestions in that case).
Thanks for reading and Have a nice day !
Advertisements

Your views on this.....

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s