UNPKG

@browser-storage/indexeddb-driver

Version:
79 lines (78 loc) 2.69 kB
import { Defer } from '@browser-storage/core'; export class IndexeddbDriver { constructor() { this._ready = new Defer(); } get isSupported() { return typeof window.indexedDB !== 'undefined'; } clear() { const objectStore = this._getObjectStore('readwrite'); return this._getRequestResult(objectStore.clear()); } // tslint:disable-next-line async destroy() { } async getItem(key) { const objectStore = this._getObjectStore('readonly'); return this._getRequestResult(objectStore.get(key)); } async hasItem(key) { const store = this._getObjectStore('readonly'); return (await this._getRequestResult(store.count(key))) > 0; } async init(dbOptions) { this._options = dbOptions; this._db = await new Promise((resolve, reject) => { const openRequest = window.indexedDB.open(this._options.name, this._options.version); openRequest.onerror = reject; openRequest.onsuccess = () => resolve(openRequest.result); openRequest.onupgradeneeded = (e) => { openRequest.result.createObjectStore(this._options.storeName); }; }); this._ready.resolve(true); return undefined; } async iterate(iterator) { const keys = await this.keys(); return keys.reduceRight(async (prev, key, index) => { await prev; const value = await this.getItem(key); await iterator(key, value, index); }, Promise.resolve()); } async key(index) { return (await this.keys())[index]; } async keys() { const objectStore = this._getObjectStore('readonly'); return this._getRequestResult(objectStore.getAllKeys()); } async length() { const objectStore = this._getObjectStore('readwrite'); return this._getRequestResult(objectStore.count()); } ready() { return this._ready.promise; } async removeItem(key) { await this._getRequestResult(this._getObjectStore('readwrite').delete(key)); } async setItem(key, item) { const objectStore = this._getObjectStore('readwrite'); await this._getRequestResult(objectStore.put(item, key)); return item; } _getObjectStore(mode) { return this._db .transaction([this._options.storeName], mode) .objectStore(this._options.storeName); } _getRequestResult(request) { return new Promise((resolve, reject) => { request.onerror = reject; request.onsuccess = () => resolve(request.result); }); } }