Skip to content

Instantly share code, notes, and snippets.

@rafaeldcastro
Last active August 15, 2021 09:04
Show Gist options
  • Save rafaeldcastro/6c48a13d45abb05c6a652ecfb61c4db5 to your computer and use it in GitHub Desktop.
Save rafaeldcastro/6c48a13d45abb05c6a652ecfb61c4db5 to your computer and use it in GitHub Desktop.
Angular - Ionic | Storage service using @ionic/storage. Wich is a reasonable abstraction to use IndexedDB
import { Injectable } from '@angular/core';
import { APP_CONSTANTS } from '@constants/app.constants';
import { Storage } from '@ionic/storage';
@Injectable({
providedIn: 'root'
})
export class StorageService {
private _storage: Storage | null = null;
constructor(private ionStorage: Storage) {
this.init();
}
async init() {
if (this._storage != null) {
return;
}
const storage = await this.ionStorage.create();
this._storage = storage;
const createdAt = <string>await this._storage.get(APP_CONSTANTS.DB_EXIST_FLAG);
if (!createdAt) {
this._storage.set(APP_CONSTANTS.DB_EXIST_FLAG, new Date().toLocaleString());
}
}
/**
* Get the value associated with the given key
* @param key Any key will be juntioned with the APP_PREFIX constant
*/
async get(key: string): Promise<any> {
// return this.storage.get(`${APP_CONSTANTS.APP_PREFIX}-${key}`)
// .then(data => data)
// .catch(e => { throw e; })
await this.init();
return await this._storage?.get(`${APP_CONSTANTS.APP_PREFIX}-${key}`);
}
/**
* Set the value for the given key
* @param key Any key will be juntioned with the APP_PREFIX constant
* @param value Any value will be stringified
*/
async set(key: string, value: any): Promise<any> {
// return this.storage.set(`${APP_CONSTANTS.APP_PREFIX}-${key}`, value)
// .then(() => true)
// .catch(e => { throw e });
await this.init();
return await this._storage?.set(`${APP_CONSTANTS.APP_PREFIX}-${key}`, value);
}
/**
* Returns a promise that resolves with an object Keys that has an
* array of strings (keys names)
*/
async keys(): Promise<string[]> {
await this.init();
return await this._storage?.keys();
}
/**
* Returns a promise that resolves with the number of keys stored
*/
async length(): Promise<number> {
await this.init();
return await this._storage?.length();
}
/**
* Remove any value associated with the given key
* @param key
*/
async remove(key: string): Promise<void> {
await this.init();
return this._storage.remove(`${APP_CONSTANTS.APP_PREFIX}-${key}`)
.then(() => console.log(`Value: ${key} removed from the Storage`))
.catch(e => { throw e; })
}
/**
* Remove ALL key value pair stored. WARNING: This can't be undone.
*/
async removeAll(): Promise<void> {
await this.init();
if(confirm('DELETE app Storage data? (cannot be reversed)')){
return this._storage.clear()
.then(() => {
console.log('Storage Deleted');
alert("Storage Deleted")
})
.catch(e => { throw e; })
} else {
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment