Ionic Storage module for Ionic apps - Ionic Templates

Jawad Ahmad
Ionic Storage module for Ionic apps

Ionic Storage

A simple storage module for Ionic apps with a key and a value. This tool uses the best storage engine on the platform without requiring direct interaction with it (some configuration is needed, see docs below).

Before version 3. x, this library only worked with Angular projects. Now, any JavaScript project can use it, and Angular-specific features have been moved to a new @ionic/storage-angular package.

Ionic Storage will use IndexedDB and local Storage by default when they are available.

Teams building security-sensitive apps that need encryption can now use Ionic Secure Storage. See Encryption Support for more information on how to use it.

Installation

npm install @ionic/storage

Install the @ionic/storage-angular library instead if you are using Angular:

npm install @ionic/storage-angular

See the SQLite Installation instructions if you want to use SQLite as a storage engine.

Usage

With Vue, React & Vanilla JavaScript

import { Storage } from '@ionic/storage';

const storage = new Storage();
await storage.create();

See the section on "Usage - API" below for a list of the methods that can be used with the storage instance.

With Angular

In Angular, you need to import the IonicStorageModule and then inject the Storage class in order to use Services and Dependency Injection.

First, add IonicStorageModule as an import to your NgModule declaration in src/app/app.module.ts or the module for the component where you'll use the storage library.

import { IonicStorageModule }
from '@ionic/storage-angular'; // Import Statement

  @NgModule({
    imports: [
..., // Other Imports
      IonicStorageModule
.forRoot()
    ]
  })
  export class AppModule { }

The next step is to add Storage to a component. This method is only meant to be used in a single component (such as AppComponent). In this situation, you should only call create() once. For use in more than one part, we suggest making a service (see next example).

import { Component } from '@angular/core'; // angular/core
import { Storage } from '@ionic/storage-angular'; // storage-angular

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {

  constructor(
private storage: Storage // Private storage
) {
  }

  async ngOnInit() {
    // await this.storage.defineDriver(YourCustomDriver)
    await this.storage.create(); // create storage
  }
}

For more advanced users, you should create an Angular Service to handle all database operations in your app and keep all configuration and initialization of the database in one place. Don't forget to register this service in a providers array in your NgModule if you're not using provided: "root," and make sure the IonicStorageModule has been initialized in that NgModule as shown above. Here's an example of how this service might look:

import { Injectable } from '@angular/core';

import { Storage } from '@ionic/storage-angular'; // Storage Import Statement

@Injectable({
  providedIn: 'root'
})
export class StorageService {
  private _storage: = null;

  constructor(private storage: Storage) {
// Call the init function below
    this.init();
  }

  async init() {
    const storage = await this.storage.create(); // Storage init
    this._storage = storage;
  }

  // Create & Expose Methods
  public set(key: string, value: any) {
    this._storage.set(key, value);
  }
}

Then, add the StorageService to your pages and any other parts that need to talk to the Storage engine.

API

The Storage API lets you set, get, and remove a key's associated value. It also allows you clear the database, look at the stored keys and how many of them there are, and list the deals in the database. To set an obj in ionic storage, use set(key, value):

await storage.set('name', 'Mr. Hammad');

To get the item back, use get(name):

const name = await storage.get('name');

To delete an item:

await storage.remove(key);

To delete all items:

await storage.clear();

To fetch all keys stored:

await storage.keys();

To get the length of stored key/value pairs:

await storage.length();

To list the key/value pairs that have been saved:

storage.forEach((key, value, index) => {
});

To use encryption with the Ionic Secure Storage driver, do the following:

storage.setEncryptionKey('mykey');

For more information, see Encryption Support below.

Configuration

The Storage engine can be set up with specific priorities for the storage engine or with custom configuration options to pass to localForage. Options can be found in the localForage configuration.

In React/Vue/Vanilla JavaScript configuration

Give the Storage constructor options for setting up the storage:

const storage = new Storage({
    name: '__dbname', // string
    driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage] // array
  });

Angular configuration

import { Drivers, Storage } from '@ionic/storage';
import { IonicStorageModule } from '@ionic/storage-angular';

@NgModule({
  imports: [
..., // Other Imports
   IonicStorageModule.forRoot({
     name: '__dbname',
     driverOrder: [
Drivers.IndexedDB, // Db index
Drivers.LocalStorage // local storage
]
   })
 ],
})
export class AppModule { }

SQLite Installation

In the 2. x version of this plugin, the localForage-cordovaSQLiteDriver had the code for it written in stone. Since SQLite 3. x, this plugin has been removed from the core code to give SQLite storage engines more options.

In SQLite 3. x, there are several good ways to use it:

  1. The old localForage-cordovaSQLiteDriver is still a good choice for non-enterprise apps, but it does not support encryption and is kept up to date by the community. Below are the instructions on how to install this plugin.

  2. We strongly suggest Ionic Secure Storage for enterprise apps. It is an enterprise SQLite engine that supports full encryption. It is fully supported & maintained by the Ionic Framework team.

localForage-CordovaSQLiteDriver

Installation

# With Cordova, install plugin with below cmd
ionic cordova plugin add cordova-sqlite-storage
# With Capacitor, install the plugin with below cmd
npm install cordova-sqlite-storage

# Once done, you can install the below npm library
npm install localforage-cordovasqlitedriver

Adding driver to configuration

If it's not Angular project, you should pass the CordovaSQLiteDriver._driver to the driverOrder config option as below:

import * as CordovaSQLiteDriver from 'localforage-cordovasqlitedriver';

const store = new Storage({
  driverOrder: [CordovaSQLiteDriver._driver, Drivers.IndexedDB, Drivers.LocalStorage]
});

In Angular Project, You need pass the same configuration when importing the IonicStorageModule in your Ionic/Angular page or app NgModule:

import * as CordovaSQLiteDriver from 'localforage-cordovasqlitedriver';

@NgModule({
  imports: [
    ..., // Other Imports
    IonicStorageModule.forRoot({
      driverOrder: [CordovaSQLiteDriver._driver, Drivers.IndexedDB]
    })
  ],
})
export class MyPageModule { }

Register Driver

Lastly, run defineDriver() on the storage instance to register the driver. Make sure to do this before any data operations:

import * as CordovaSQLiteDriver from 'localforage-cordovasqlitedriver';

await this.storage.defineDriver(CordovaSQLiteDriver);

Using Ionic Secure Storage

Ionic Secure Storage is a high-performance data store ready for enterprise use. It works with SQL or key/value pairs and has 256-bit AES encryption. When used with Ionic Identity Vault, developers can safely manage encryption keys and build fully offline apps with biometric authentication using all of the security features on modern mobile devices and operating systems.

Ionic Secure Storage is a business product, so you need an active business subscription or trial. Visit the Secure Storage product page to find out more and ask for a demo.


Installation

You should follow the official installation guide to set up and install plugin: @ionic-enterprise/secure-storage.

Usage

With Vue, React & Vanilla JavaScript

import { Drivers } from '@ionic/storage';
import IonicSecureStorageDriver from '@ionic-enterprise/secure-storage/driver';

const store = new Storage({
  driverOrder: [Drivers.SecureStorage, Drivers.IndexedDB, Drivers.LocalStorage]
});

await store.defineDriver(IonicSecureStorageDriver);

With Angular

In Angular, you must import the IonicStorageModule and inject the Storage Class to use Services and Dependency Injection.

First, add IonicStorageModule as an import to your NgModule declaration in src/app/app.module.ts or the module for the page where you'll use the storage library.

import { Drivers } from '@ionic/storage';
import { IonicStorageModule } from '@ionic/storage-angular';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    IonicStorageModule.forRoot({
// Driver
      driverOrder: [Drivers.SecureStorage, Drivers.IndexedDB, Drivers.LocalStorage]
    })
  ],
})
export class AppModule { }

After this. register the "driver" in your app component:

  async ngOnInit() {
    await this.storage.defineDriver(IonicSecureStorageDriver); // Define Your Driver
    await this.storage.create(); // Register Your Storage
  }

Once this done, you should follow the instructions below to configure encryption support:

Encryption Support

3. x adds a new method called set encryption key that lets Ionic Secure Storage work with encryption (see instructions above).

It is an enterprise feature for teams that need a lot of security. You can use the simple @ionic/storage key-value API or switch to SQL for more powerful querying and support for relational data; everything is encrypted. Teams can safely manage encryption keys and provide biometric authentication online or offline when paired with Ionic Identity Vault.

Visit the Secure Storage product page to learn more about it and ask for a trial.

Encrypting an Existing SQLite Database

To switch to a new, encrypted database powered by Ionic Secure Storage, you must do a one-time migration.

First, follow the steps above to update Ionic Storage v3, install the local forage-CordovaSQLiteDriver SQLite driver, and integrate Ionic Secure Storage.

Next, take the database name and drivers out of app.module.ts if they were there:

@NgModule({
    imports: [
      ..., // Other Imports
      IonicStorageModule.forRoot()
    ],
 
  })
  export class MyPageModule { }

Last, make a one-time migration function in the service class that moves data to an encrypted database. Run this function when the app starts up.


async onMigrateDatabase() {
    const orignalStore = new Storage({
      name: 'originalDBName', // the original database name
      driverOrder: [CordovaSQLiteDriver._driver, Drivers.IndexedDB, Drivers.LocalStorage]
    });
    await orignalStore.defineDriver(CordovaSQLiteDriver);
 
    const newStor = new Storage({
      name: 'encryptedDBName', // pick a new db name for the encrypted db
      driverOrder: [Drivers.SecureStorage, Drivers.IndexedDB, Drivers.LocalStorage]
    });
    await newStor.defineDriver(IonicSecureStorageDriver);
    newStor.setEncryptionKey('mykey');
 
    if (await orignalStore.length() > 0) {
      // copy existing (orignalStore) data into new const variable, encrypted format
      await orignalStore.forEach((key, value, index) => {
        newStor.set(key, value);
      });
 
      // remove old data
      await orignalStore.clear();
    }
 
    this._storage = newStor;
  }

Conclusion:

You did a good job! Guys, this is the end of this post. I hope this post was helpful and that you had a lot of fun. If you're having trouble or want me to write about something else, let me know in the comments, and I'll help you.

Thank You!

Ba Bye !


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !