Creating an IndexedDB database

Author: Damian Gemza

-

Creating the databases — IndexedDB

IndexedDB is a low-level API for the client-side storage of significant amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data.

Installing the IndexedDB package:

To interact with Indexed DB, we use a small but convenient tool called idb. It is a wrapper for the IndexedDB API which provides a more convenient way to use this database. In order to install idb in your application, run the following command in the application terminal:


        npm install idb --save
      

After installing the idb library, we have to create a service that will allow us to operate on the Indexed DB database. To do this, run the following command in the application terminal and then open the IdbService file.


        ng generate service services/idb
      

After creating the IdbService, please copy the code below there:


        import {Injectable} from '@angular/core';
        import idb from 'idb';
        import {Observable, Subject} from 'rxjs';
        import {Schedule} from '../app.component';

        @Injectable({
          providedIn: 'root'
        })
        export class IdbService {
        private _dataChange: Subject<Schedule> = new Subject<Schedule>();
        private _dbPromise;

        constructor() {
        }

        connectToIDB() {
          this._dbPromise = idb.open('pwa-database', 1, UpgradeDB => {
            if (!UpgradeDB.objectStoreNames.contains('Items')) {
              UpgradeDB.createObjectStore('Items', {keyPath: 'id', autoIncrement: true});
            }
            if (!UpgradeDB.objectStoreNames.contains('Sync-Items')) {
              UpgradeDB.createObjectStore('Sync-Items', {keyPath: 'id', autoIncrement: true});
            }
          });
        }

        addItems(target: string, value: Schedule) {
          this._dbPromise.then((db: any) => {
            const tx = db.transaction(target, 'readwrite');
            tx.objectStore(target).put({
            time: value.time,
            subject: value.subject,
            location: value.location,
            description: value.description
          });
          this.getAllData('Items').then((items: Schedule) => {
            this._dataChange.next(items);
          });
            return tx.complete;
          });
        }

        deleteItems(target: string, value: Schedule) {
          this._dbPromise.then((db: any) => {
            const tx = db.transaction(target, 'readwrite');
            const store = tx.objectStore(target);
            store.delete(value);
            this.getAllData(target).then((items: Schedule) => {
              this._dataChange.next(items);
            });
          return tx.complete;
          });
        }

        getAllData(target: string) {
          return this._dbPromise.then((db: any) => {
            const tx = db.transaction(target, 'readonly');
            const store = tx.objectStore(target);
            return store.getAll();
          });
        }

        dataChanged(): Observable<Schedule> {
            return this._dataChange;
          }
          }


      

How does Indexed DB and idb work? Originally, the Indexed DB API is based on events. This solution is uncomfortable and non-intuitive, resulting in a tool such as idb, which is a wrapper for the original Indexed DB API. The main construction of idb is the Promise, through which the resolve we have access to the specific data.

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

A Promise.resolve() is shortcut to manually create an already resolved promise respectively.

How does IdbService work? The connectToIDB() method creates a new database with two stores. One store will store data acquired from the online mode, while the second one serves as a buffer for offline mode. When we add events offline and then go online, the buffer will be cleared and the data it has stored will then be sent to the Firebase database.

The addItems() method uses target and value as arguments. After resolving the promise, we create a new transaction for a specific store (target), then we put data from the value argument in it, and then we emit a data change through this._dataChange which is defined as a Subject.

The deleteItems() method works similarly to the addItems() method, but it removes objects from the Indexed DB database.

The getAllData() method returns the whole store from the IndexedDB which is determined by the target parameter.

The dataChanged() method returns the this._dataChange subject. This allows us to subscribe to the data change.

Is it working for you? If not, check the code for this lesson in our repository


Rate this lesson

Previous lesson Download Next lesson

Spread the word:
Do you need help? Use our support forum

About the author

User avatar
Damian Gemza
Damian is a front-end developer. He is passionate about everything related to the world of Web Development. He is interested in Angular and everything that is connected with it. He knows and uses the Ionic framework and Progressive Web Apps technology. Recently he has started to write tutorials related to Web Development.

Install MDB CLI
It's the fastest way to create and host MDB projects
Free Download

Sign up to follow your progress and get additional benefits