UJJWAL GUPTA
Posted on May 15, 2019
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.
In this article, I am going to describe how we can do CRUD operation in indexeddb using jsstore. 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
Let's 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
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.
<!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.
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 = {
// Id: 1,
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. In that case we need to fliter row & JsStore provides - where
to filter data. So 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
JStore 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.
Reference
Posted on May 15, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.