Conversation


Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!

Join the discussion and share your insights now!

Comments 0


advertisement

How to Use Indexed Database API for Efficient Web Storage

Indexed Database API


Indexed Database API

A database is an organized collection of data. Databases, such as relational databases store data in the form of tables. A table comprises rows and columns that are used to store data. The representation of data in a table is in the form of records.

HTML5 has introduced a new Web Storage API that can host Web databases locally within the user browser. However, Web databases are not like relational databases in terms of functionality.

Indexed Database API is a specification also known as IndexedDB. It is an object store that can be used to store and manipulate data on the client side. The object store is the primary storage mechanism that stores the object in the database and manages it locally within the browser. It enables the creation of an object store of a particular type in which objects can be persisted using JavaScript. Thus, IndexedDB enables the creation of Web applications with rich query abilities that can work both online and offline.

IndexedDB supports two types of API namely synchronous and asynchronous. The synchronous API can be used with WebWorkers, whereas the asynchronous API can be used for Web applications. Currently, no major browsers provide support for the synchronous API.

The IndexedDB API is implemented using Windows. IndexedDB object. As the current specification is still in its evolving stage, browsers implement the IndexedDB object with their prefixes. For example, the Chrome browser uses the webkit prefix, whereas Mozilla supports the -moz prefix.

Lists browser support for the IndexedDB API.

Browser Support for IndexedDB API



1. IndexedDB API

Some of the basic constructs of the IndexedDB API are as follows:


  1. Database - The IndexedDB database comprises more than one object store. Each database contains a name that identifies the origin of the database and a version number that identifies the lifetime of the database.

  2. Object Store - The object store is the main mechanism to store data in a database. They hold the data stored in the database in the form of records.

  3. Keys - Each record stored in the database is identified by a unique key.

  4. Values - Values are the data stored in the records.

  5. Key Path - A key path is a string that defines how the browser should extract the key from a value. The key to a value can be extracted either from the object store or index. An empty string, a JavaScript identifier, and so on are some of the valid key paths.

  6. Index - It is used when the data from the object store is retrieved based on some other value other than a key. It is a specialized object store that searches for records in another object store known as a referenced object store.

  7. Transaction - Any addition or retrieval of data in a database is performed by using a transaction. In other words, it is a mechanism used for interacting with the database. Each transaction has a mode, scope, and request list. The mode determines the type of transaction that can be performed, the scope identifies the object store on which the transaction will be performed, and finally, the request list determines the requests that have been made.

  8. Requests - Operations, such as reading or writing to the database are performed using a request. Each request contains attributes, such as flag, source object, result, and error.

  9. Cursor - A cursor is a mechanism used to retrieve multiple records from a database.

  10. Key Range - Records from the object stores and indexes are retrieved using keys or key ranges. A key range refers to the retrieval of data between specified bounds based on keys.


2. Implementing the IndexedDB API

The steps to implement the IndexedDB API in a Web application are as follows:


  • Open a database
  • Create an object store
  • Start a transaction
  • Perform some database operations, such as add and retrieve
  • Work with the retrieved results



I. Opening a database

The code opens a database.


const indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
const request = indexedDB.open("CompanyDB", 1);
request.onsuccess = function(event) {
    console.log("IndexedDB opened successfully.");
};
request.onerror = function(event) {
    console.log("IndexedDB error: " + event.target.errorCode);
};

Here, the code detects support for the IndexedDB API in different browsers and creates the IndexedDB object. The indexedDB object contains a method named open () which opens the CompanyDB database.

In case the database exists, then the open () method simply opens it, otherwise it creates the database.

The open() method returns an IDBRequest object named request. The request object provides handlers, such as success and error. These handlers are invoked depending on the success or failure of opening the database. The onsuccess () handler contains an event of type success as its argument. Similarly, the onerror () handler is invoked with an error event as its argument.


II. Updating version of a Database

After the database is opened, it can be structured by providing a version number. This helps us to set up the database.

The version number will be specified in a database in the onsuccess () function.

The code that specifies the version number of the database CompanyDB.

const setVrequest = db. setVersion ("1.99");
setVrequest.onsuccess = function (event) {
...
};


III. Creating the Object Store

The structure of the IndexedDB database facilitates the storage of multiple object stores. In other words, there can be more than one object stored in the database. The object store is created using the createObjectStore() method. The createObjectStore() method accepts two arguments namely, the store name and a parameter object. The parameter object is used for defining an optional property which is important. In this case, a key path is defined which is used for identifying unique objects in the object store. For example, an employee store contains the ID property as the key path, which will be unique for each object and must be present for each object.

The code creates an object store named employee in the CompanyDB database.

var employeeData = [
    { name: "John Smith", email: "john@company.com" },
    { name: "Jill Patrick", email: "jill@company.com" },
    { name: "Rock Ethan", email: "rock@company.com" },
    { name: "Daniel Andrew", email: "daniel@company.com" }
];
var objectStore = db.createObjectStore("employee", {
    keyPath: "id",
    autoIncrement: true
});
for (var i in employeeData) {
    objectStore.put(employeeData[i]);
}
alert("Record added");

The code creates an array named employeeData containing name and e-mail values. Then, the createObjectStore () method creates an employee store with its key path set to the ID attribute. The key path is used with the autoIncrement option that automatically generates an ID for each of the objects. All individual objects in the object store are identified based on their ID. Finally, the for..in loop stores the data in the employee object-store.


IV. Creating a transaction

To perform database operations, such as retrieving data from the object store, Indexed DB provides an IDBTransaction object. This object can be created in three modes namely, read-only, read-write, and snapshot. The read-write mode is used to update the object, whereas the read-only mode is used for other operations.

The code retrieves data from the employee object store using the get () function of the transaction object.

var trans = db.transaction(["employee"], "readwrite");
var objectStore = trans.objectStore("employee");
var request = objectStore.get(2);
request.onerror = function(event) {
    // Handle errors
    console.log("Error fetching data: " + event.target.errorCode);
};
request.onsuccess = function(event) {
    // Do something with the request.result
    alert("Name: " + request.result.name);
};

In the code, the transaction() method accepts two parameters. The second parameter is optional. The first parameter is the list of object stores that are extended by the transaction object. In this case, there is a single object store named employee, created in the database. The optional second parameter specifies the type of the transaction, that is, read-only, read-write, or snapshot. Here, the transaction type is defined as readwrite. This type allows reading as well as writing to the database. The employee object store is retrieved from the transaction object on which operations are performed. Here, the get () method is invoked on the employee object store which returns the value against the key path 2. Finally, the result of the get () method is stored in the request object on which callback functions, such as onsuccess and onerror are invoked.


V. Open the cursor

The cursor is used to retrieve multiple records from an object store. They can be used when the value of the key path is not known. They are part of a transaction and are opened for a particular object-store.

The code retrieves multiple records from the employee object-store.

var store = db.transaction(["employee"], "readonly").objectStore("employee");
store.openCursor().onsuccess = function(event) {
    var cursor = event.target.result;
    if (cursor) {
        alert("Name for id " + cursor.key + " is " + cursor.value.name);
        cursor.continue();
    }
};

Here, in the code, the transaction object is created for the employee object-store. Then, the openCursor() function is invoked in the object store. If the cursor is successfully opened, a Cursor object is returned which will retrieve the data from the object store.



3. Limitations of the IndexedDB API

The Indexed DB API is used for client-side data storage but has some design limitations. These limitations are as follows:

  1. International sorting deals with sorting string data. As the database does not follow any international order for storing data, the API does not support international sorting.

  2. The IndexedDB API does not synchronize the client-side database with the server-side database. If required, then code must be written to perform server-side synchronization.

  3. The IndexedDB API supports querying the client-side database but does not support the use of operators, such as LIKE, which is used by Structured Query Language (SQL). SQL is a query language used by server-side databases to operate the database.


HTML5 API IndexedDB API Indexed Database API Web Storage API Implementing the IndexedDB API HTML IndexedDB API

advertisement