1
私はindexedDBをロードするクラスを持っています。クラスのメソッドがアクセスできるようになる前に、事前にindexedDBをロードする必要があります。現在私はthis.db
が初期化されていない他の方法よりも先にinit()
メソッドを使用しています。クラス内で非同期のindexedDBを実装するためのきれいな方法
私は自分が持っているものを実装するためのよりクリーンな方法を探していますが、間違いなくDRYではありません。本質的にすべてのメソッドは現在以下のコードパターンで実装されています。
問題点である:
- 別の方法
init()
の要件適切 のIndexedDBを使う初期を処理するために。 if (!this.db) {
セグメントは後でそれ自体を繰り返すことになります。
export default class Persist {
constructor(storage) {
if (storage) {
this.storage = storage;
}
else {
throw new Error('A storage object must be passed to new Persist()');
}
}
// needed to ensure that indexedDB is initialized before other methods can access it.
init() {
// initialize indexedDB:
const DBOpenRequest = this.storage.open('db', 1);
DBOpenRequest.onupgradeneeded =() => {
const db = DBOpenRequest.result;
db.createObjectStore('db', { keyPath: 'id', autoIncrement: true });
};
return new Promise((resolve, reject) => {
DBOpenRequest.onerror = event => {
reject(event);
};
DBOpenRequest.onsuccess = event => {
console.log(`IndexedDB successfully opened: ${event.target.result}`);
resolve(event.result);
this.db = DBOpenRequest.result;
};
});
}
toStorage(session) {
if (!this.db) {
return this.init().then(() => {
const db = this.db;
const tx = db.transaction('db', 'readwrite');
const store = tx.objectStore('db');
const putData = store.put(session.toJS());
return new Promise((resolve, reject) => {
putData.onsuccess =() => {
resolve(putData.result);
};
putData.onerror =() => {
reject(putData.error);
};
});
});
}
// basically a repeat of above
const db = this.db;
const tx = db.transaction('db', 'readwrite');
const store = tx.objectStore('db');
const putData = store.put(session.toJS());
return new Promise((resolve, reject) => {
putData.onsuccess =() => {
resolve(putData.result);
};
putData.onerror =() => {
reject(putData.error);
};
});
}
これを書いてくれてありがとうございました。私はあなたのポストからかなり学んだ!実際に、私は最終的に 'async/await'を初めて使用するようになりました:)。 – mythereal