Monday, April 22, 2019

HTML internal storage with IndexedDB

One of the challenge in modern web application is to store data in client side, it can help to avoid un-necessary service call to server. IndexedDB is one of the mechanism which will store data in client browser (hence it is crucial that browser should support it). Below are some of scenario for keeping data local

1. Text Translation - load all translated text in browser and avoid service call for text translation
2. work offline - this will help to reduce round trip. Load all data at the time of application load (ex: Types/Categories etc) so that we dont needs to call service to fetch again.
3. Work Offline - store all data in indexedDB, and continue process, once everything is completed, single click can save data in your SQL/Oracle DB.

Fact about IndexedDB

1. It is not a RDBMS
2. Data are stored in the form of key/value
3. SQL query will not work
4. IndexedDB is not a replacement of your DB
5. User can group a set of key/value and Keypath will represent each key/value pair

lets start practical :)

below is HTML will create IndexedDB and store (try this in your chrome)
Full Source code available here

<html>
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = utf-8" />
<script type = "text/javascript">
//prefixes of implementation that we want to test
window.indexedDB = window.indexedDB || window.mozIndexedDB ||
window.webkitIndexedDB || window.msIndexedDB;
//prefixes of window.IDB objects
window.IDBTransaction = window.IDBTransaction ||
window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange ||
window.msIDBKeyRange
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.")
}
var db;
var request = window.indexedDB.open("empDB", 1);
request.onerror = function(event) {
console.log("error: ");
};
request.onsuccess = function(event) {
db = request.result;
console.log("db Created success: "+ db);
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("empstore", {keyPath: "empid"});
}
</script>
</head>
<body> </body>
</html>

save as HTML file and run.
Once page loaded, you will be seeing blank screen :), lets see what is happening indexedDB, press F12 and select application tab, your IndexedDB, store are ceated now :)

















lets go through the code. Below code creates new Indexed DB empDB (line no: 17)
var request = window.indexedDB.open("empDB", 1);

below line will be creating an object store named empStore (line no 27). I set keypath as empID. KeyPath (empID) is one of property in key/value collection, which will represent the entire group (like PK in RDBMS)

var objectStore = db.createObjectStore("empstore", {keyPath: "empid"});

Now I am going to add/Find/Delete data from my IndexedDB

below, i am adding HTML tag to add/Find/Delete. I am adding 3 textbox which will have empID, Name and Age.

<body>
<label>Emp ID</label><input type="text" id="txtEmpID"><br/>
<label>Emp Name</label><input type="text" id="txtEmpName"><br/>
<label>Emp Age</label><input type="text" id="txtAge"><br/><br/>

<button onclick = "add()">Add data </button>
<button onclick = "read()">Find </button>
<button onclick = "remove()">Delete data </button>
</body>

Add to IndexedDB
function add() {

var _empID = txtEmpID.value;
var _empName=txtEmpName.value;
var _empAge=txtAge.value;
var request = db.transaction(["empstore"], "readwrite")
.objectStore("empstore")
.add({ empid: _empID.toString(), name: _empName.toString(), age: _empAge.toString()});
request.onsuccess = function(event) {
alert("Employee has been added to your database.");
};
request.onerror = function(event) {
alert("Unable to add data\r\nEmployee is aready exist in your database! ");
}
}

now refresh your indexedDB you could find the entry in key/value pair form like below





Find


function read() {
var _empID = txtEmpID.value;
var transaction = db.transaction(["empstore"]);
var objectStore = transaction.objectStore("empstore");
var request = objectStore.get(_empID.toString());
request.onerror = function(event) {
alert("Unable to retrieve daa from database!");
};
request.onsuccess = function(event) {
// Do something with the request.result!
if(request.result) {
alert("Name: " + request.result.name + ", Age: " + request.result.age );
} else {
alert("Employee couldn't be found in your database!");
}
};
}

Delete
function remove() {
var _empID = txtEmpID.value;
var request = db.transaction(["empstore"], "readwrite")
.objectStore("empstore")
.delete(_empID.toString());
request.onsuccess = function(event) {
alert("EMployee has been removed from your database.");
};
request.onerror = function(event) {
alert("Employee not found ");
}
}

No comments: