Getting Started With IndexedDB Using JsStore

Introduction

 
IndexedDB is a NoSQL database technology in HTML5 which allows storing the data and doing different database operations in the browsers. 
 
Properties of IndexedDB.
  • It is a NoSQL Database technology.
  • It provides multiple APIs for different database operations. All APIs are async.
  • It allows to store files in the form of blobs.
  • It uses indexes to enable high performance search in the data.
  • It is an alternative to WebSQL since WebSQL is now deprecated.
Problem
 
IndexedDB is very good but every developer finds it so complex because of so many APIs and those APIs are of low level. 
 
Now the question arises, what a low-level API is.
 
Low-level API is something like low-level languages, such as C, Assembly language etc. Now, consider the coding in C# and coding in C - You will agree that you can learn and start coding in C# very easily and in very less time while coding in C takes time as you need to write everything and need to handle everything like - freeing resources, garbage collection etc. all by yourself.
 
I believe everyone who is in the IT field has learned SQL as a primary language. Now, SQL is so famous that we think the DB in terms of the SQL. 
 
While IndexedDB is completely new and there is no relation with SQL, this also makes it another reason to be complex. I had the same issue and wanted to use IndexedDB for offline storage - but it was so tough for me to use IndexedDB. I was thinking in SQL and was trying to convert my thought as indexeddb but no luck.
 
So, I found a library called JsStore. It is an IndexedDB wrapper which provides SQL like APIs. This makes things so easy that you can create a working application within an hour.
 
The awesome thing is that it provides so many examples for different tools and frameworks which helps you to understand and develop things very fast and easily. 
 
So, in this article, I am going to describe how we can do CRUD operation. I am going to explain the example given by JsStore. So, if you want to have a look or want to use it. Here is the link.
 
https://github.com/ujjwalguptaofficial/JsStore/tree/master/examples/Simple%20Example
 
Code
 
First, create an HTML page, let's say index.html. Paste the below code inside index.html.
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <meta http-equiv="X-UA-Compatible" content="ie=edge">  
  7.     <title>Crud Demo using jsstore</title>  
  8. </head>  
  9. <body>  
  10.  
  11. </body>  
  12. </html>  
Installation
 
There are different ways to install JsStore. Check out the installation doc - http://jsstore.net/tutorial/installation/
 
In this article, I am going to download JsStore from the official repository. Download the repo from https://github.com/ujjwalguptaofficial/JsStore and unzip it. Now, open the folder and navigate to - dist folder. There, you will see many files. For this article, we need to copy two files - jsstore.min.js, jsstore.worker.min.js. 
 
Let's include the script in the HTML page, so now, our HTML becomes.
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <meta http-equiv="X-UA-Compatible" content="ie=edge">  
  7.     <title>Crud Demo using jsstore</title>  
  8.     <script src="jsstore.min.js"></script>  
  9. </head>  
  10. <body>  
  11. <h4>We have included JsStore in this html code.</h4>  
  12. </body>  
  13. </html>  
Now, we need to initiate the JsStore in order to use. You can see that in line 13, I have created an instance of JsStore and stored it in a variable connection.
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <meta http-equiv="X-UA-Compatible" content="ie=edge">  
  7.     <title>Crud Demo using jsstore</title>  
  8.     <script src="jsstore.min.js"></script>  
  9. </head>  
  10. <body>  
  11. <h4>We have included JsStore in this html code.</h4>  
  12. <script>  
  13. var connection = new JsStore.Instance(new Worker('jsstore.worker.js'));  
  14. </script>  
  15. </body>  
  16. </html>  
Now, the variable - "connection" will be used to perform the database operation. Also, the instance doesn't need to be created again and again. It is just one time at the start of the application.
 
Note
 
When you open the HTML file, you will see an error in the browser. That is because the worker is not accessible in the file protocol in some browsers, like Chrome. So, please use an HTTP Server for making it work.
 
Create Database 
 
JsStore follows SQL approach to create a database - A database consists of tables and a table consists of columns. Let's see how to create a database schema in JsStore.
  1. function getDatabase() {  
  2.     var tblStudent = {  
  3.         name: "Student",  
  4.         columns: [{  
  5.                 name: "Id",  
  6.                 primaryKey: true,  
  7.                 autoIncrement: true  
  8.             },  
  9.             {  
  10.                 name: "Name",  
  11.                 notNull: true,  
  12.                 dataType: "string"  
  13.             },  
  14.             {  
  15.                 name: "Gender",  
  16.                 dataType: "string",  
  17.                 default'male'  
  18.             },  
  19.             {  
  20.                 name: "Country",  
  21.                 notNull: true,  
  22.                 dataType: "string"  
  23.             },  
  24.             {  
  25.                 name: "City",  
  26.                 notNull: true  
  27.             }  
  28.         ]  
  29.     }  
  30.     var dataBase = {  
  31.         name: "Students",  
  32.         tables: [tblStudent]  
  33.     }  
  34.     return dataBase;  
  35. }  
So what we have done.
  1. Created a function 'getDataBase' which will return the database schema.
  2. Inside the function, we have created a table - tblStudent. tblStudent has a property Columns which contains a list of columns.
  3. A database is created with the name - "students" and tblStudent is passed to the database.
The interesthing thing to note here is that - we are using options like : autoIncrement, default, notNull etc. which is not supported by default in indexedDb. But jsstore provides it.  
 
Now, we have easily created the DB schema. But the database is not created yet.
  
Now, let's create the DB.
  1. function initiateDb() {  
  2.     var DbName = "Students";  
  3.     connection.isDbExist(DbName).then(function(isExist) {  
  4.         if (isExist) {  
  5.             connection.openDb(DbName).then(function() {  
  6.                 console.log('db opened');  
  7.             });  
  8.             showTableData();  
  9.         } else {  
  10.             var DataBase = getDatabase();  
  11.             connection.createDb(DataBase).then(function(tables) {  
  12.                 console.log(tables);  
  13.             });  
  14.         }  
  15.     }).catch(function(err) {  
  16.         console.log(err);  
  17.         alert(err.message);  
  18.     });  
  19. }  
The above function, when called, checks whether a database is created or not. If it is created, then we open the DB, otherwise create the DB. You can see we are calling getDatabase for getting db schema and then passing it to createDb API.
 
Now, we need to call the initiateDb - we will call this in onload event. 
  1. window.onload = function() {  
  2.     initiateDb();  
  3. };  
When the page is loaded  - the connection variable is initialized and db is created or opened. When you create db, JsStore also opens the db connection.
 
So, now the connection variable knows that this is the database with which you want to perform the operations.
 
Insert Data
 
JsStore provides Insert API for inserting the data. Check out insert doc. We have created a table ' Student ' which has the columns - Id, Name, Gender, Country, City.
 
So a row (value) in the table student will be - 
  1. var value = {  
  2.     Id: 1,  
  3.     Name: 'durgesh',  
  4.     Gender: 'male',  
  5.     Country: 'India',  
  6.     City: 'efr'  
  7. }  
But the Id is autoIncrement column, so we should not supply the value.
 
Now, let's insert the above values in table.
  1. var value = {  
  2.     // Id: 1,  
  3.     Name: 'ffff',  
  4.     Gender: 'male',  
  5.     Country: 'USA',  
  6.     City: 'efr'  
  7. }  
  8.   
  9. connection.insert({  
  10.     into: "Student",  // table name
  11.     values: [value]  
  12. }).then(function(rowsAdded) {  
  13.     if (rowsAdded > 0) {  
  14.         alert('Successfully added');  
  15.     }  
  16. }).catch(function(err) {  
  17.     console.log(err);  
  18.     alert('Error Occured while adding data')  
  19. });  
In the above code, we are calling the Insert API, passing the table name, and values to insert. 
 
Read Data
 
JsStore has Select API for reading the data. Check out select docs for more info. So, let's say we want to read all the data in a table. The query will be like following.
  1. connection.select({  
  2.     from: "Student"  
  3. }).then(function(datas) {  
  4.     console.log(datas);  
  5. }).catch(function(err) {  
  6.     console.log(err);  
  7. });  
Now, let's say we want to select data from student whose id is 1, then the query will be like below.
  1. connection.select({  
  2.     from: "Student",  
  3.     where: {  
  4.         Id: 1  
  5.     }  
  6. }).then(function(datas) {  
  7.     console.log(datas);  
  8. }).catch(function(err) {  
  9.     console.log(err);  
  10. });  
Update Data
 
JsStore provides Update API for updating the data. Check out update docs. So, let's say we want to update the student name whose id is 1, then the query will be like.
  1. connection.update({  
  2.     in"Student",  
  3.     where: {  
  4.         Id: 1  
  5.     }  
  6. }).then(function(rowsUpdated) {  
  7.     console.log(rowsUpdated);  
  8. }).catch(function(err) {  
  9.     console.log(err);  
  10. });  
Delete Data
 
JsStore provides delete API for deleting the data. Check out update docs. Let's say we want to delete a student whose id is 2, then the query will be like below.
  1. connection.remove({  
  2.     from: "Student",  
  3.     where: {  
  4.         Id: 2  
  5.     }  
  6. }).then(function(rowsDeleted) {  
  7.     console.log(rowsDeleted);  
  8. }).catch(function(err) {  
  9.     console.log(err);  
  10. });  
Summary
 
JsStore makes IndexedDB very simple and easy with its SQL like API. If you know SQL, then you already know the JsStore, you just have to start coding.
 
References
  • http://jsstore.net/tutorial/get-started/
  • https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  • https://github.com/ujjwalguptaofficial/JsStore/blob/master/examples/Simple%20Example/index.html