// Copyright Epic Games, Inc. All Rights Reserved. "use strict"; //////////////////////////////////////////////////////////////////////////////// export class Cache { constructor(db_name, ...store_names) { this._db_name = db_name; this._store_names = store_names; this._version = 2; this._db = this._open(); } put(store_name, key, value) { const executor = async (resolve, reject) => { const db = await this._db; const transaction = db.transaction(store_name, "readwrite"); const store = transaction.objectStore(store_name); const request = store.put(value, key); request.onerror = (evt) => reject(Error("put transaction error")); request.onsuccess = (evt) => resolve(true); }; return new Promise(executor); } get(store_name, key) { const executor = async (resolve, reject) => { const db = await this._db; const transaction = db.transaction(store_name, "readonly"); const store = transaction.objectStore(store_name); const request = store.get(key); request.onerror = (evt) => reject(Error("get transaction error")); request.onsuccess = (evt) => { if (request.result) resolve(request.result); else resolve(false); }; }; return new Promise(executor); } _open() { const executor = (resolve, reject) => { const request = indexedDB.open(this._db_name, this._version); request.onerror = (evt) => reject(Error("Failed to open IndexedDb")); request.onsuccess = (evt) => resolve(evt.target.result); request.onupgradeneeded = (evt) => { const db = evt.target.result; for (const store_name of db.objectStoreNames) db.deleteObjectStore(store_name) for (const store_name of this._store_names) db.createObjectStore(store_name); }; }; return new Promise(executor); } }