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.
Code
First, create an HTML page, let's say index.html. Paste the below code inside index.html.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Crud Demo using jsstore</title>
- </head>
- <body>
-
- </body>
- </html>
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.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Crud Demo using jsstore</title>
- <script src="jsstore.min.js"></script>
- </head>
- <body>
- <h4>We have included JsStore in this html code.</h4>
- </body>
- </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.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Crud Demo using jsstore</title>
- <script src="jsstore.min.js"></script>
- </head>
- <body>
- <h4>We have included JsStore in this html code.</h4>
- <script>
- var connection = new JsStore.Instance(new Worker('jsstore.worker.js'));
- </script>
- </body>
- </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.
- function getDatabase() {
- var tblStudent = {
- name: "Student",
- columns: [{
- name: "Id",
- primaryKey: true,
- autoIncrement: true
- },
- {
- name: "Name",
- notNull: true,
- dataType: "string"
- },
- {
- name: "Gender",
- dataType: "string",
- default: 'male'
- },
- {
- name: "Country",
- notNull: true,
- dataType: "string"
- },
- {
- name: "City",
- notNull: true
- }
- ]
- }
- var dataBase = {
- name: "Students",
- tables: [tblStudent]
- }
- return dataBase;
- }
So what we have done.
- Created a function 'getDataBase' which will return the database schema.
- Inside the function, we have created a table - tblStudent. tblStudent has a property Columns which contains a list of columns.
- 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.
- function initiateDb() {
- var DbName = "Students";
- connection.isDbExist(DbName).then(function(isExist) {
- if (isExist) {
- connection.openDb(DbName).then(function() {
- console.log('db opened');
- });
- showTableData();
- } else {
- var DataBase = getDatabase();
- connection.createDb(DataBase).then(function(tables) {
- console.log(tables);
- });
- }
- }).catch(function(err) {
- console.log(err);
- alert(err.message);
- });
- }
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.
- window.onload = function() {
- initiateDb();
- };
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 -
- var value = {
- Id: 1,
- Name: 'durgesh',
- Gender: 'male',
- Country: 'India',
- City: 'efr'
- }
But the Id is autoIncrement column, so we should not supply the value.
Now, let's insert the above values in table.
- var value = {
-
- Name: 'ffff',
- Gender: 'male',
- Country: 'USA',
- City: 'efr'
- }
-
- connection.insert({
- into: "Student", // table name
- values: [value]
- }).then(function(rowsAdded) {
- if (rowsAdded > 0) {
- alert('Successfully added');
- }
- }).catch(function(err) {
- console.log(err);
- alert('Error Occured while adding data')
- });
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.
- connection.select({
- from: "Student"
- }).then(function(datas) {
- console.log(datas);
- }).catch(function(err) {
- console.log(err);
- });
Now, let's say we want to select data from student whose id is 1, then the query will be like below.
- connection.select({
- from: "Student",
- where: {
- Id: 1
- }
- }).then(function(datas) {
- console.log(datas);
- }).catch(function(err) {
- console.log(err);
- });
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.
- connection.update({
- in: "Student",
- where: {
- Id: 1
- }
- }).then(function(rowsUpdated) {
- console.log(rowsUpdated);
- }).catch(function(err) {
- console.log(err);
- });
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.
- connection.remove({
- from: "Student",
- where: {
- Id: 2
- }
- }).then(function(rowsDeleted) {
- console.log(rowsDeleted);
- }).catch(function(err) {
- console.log(err);
- });
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