From 79069d59085e4fa50599052381b8f2c0d22270aa Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Thu, 31 Oct 2019 21:10:56 -0400 Subject: Add functions for getting dictionary information --- ext/bg/js/database.js | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) (limited to 'ext/bg/js') diff --git a/ext/bg/js/database.js b/ext/bg/js/database.js index 9f477b24..fc0af049 100644 --- a/ext/bg/js/database.js +++ b/ext/bg/js/database.js @@ -202,6 +202,60 @@ class Database { return this.db.dictionaries.toArray(); } + async getDictionaryInfo() { + this.validate(); + + const results = []; + const db = this.db.backendDB(); + const dbTransaction = db.transaction(['dictionaries'], 'readonly'); + const dbDictionaries = dbTransaction.objectStore('dictionaries'); + + await Database.getAll(dbDictionaries, null, null, info => results.push(info)); + + return results; + } + + async getDictionaryCounts(dictionaryNames, getTotal) { + this.validate(); + + const objectStoreNames = [ + 'kanji', + 'kanjiMeta', + 'terms', + 'termMeta', + 'tagMeta' + ]; + const db = this.db.backendDB(); + const dbCountTransaction = db.transaction(objectStoreNames, 'readonly'); + + const targets = []; + for (const objectStoreName of objectStoreNames) { + targets.push([ + objectStoreName, + dbCountTransaction.objectStore(objectStoreName).index('dictionary') + ]); + } + + const totalPromise = getTotal ? Database.getCounts(targets, null) : null; + + const counts = []; + const countPromises = []; + for (let i = 0; i < dictionaryNames.length; ++i) { + counts.push(null); + const index = i; + const only = IDBKeyRange.only(dictionaryNames[i]); + const countPromise = Database.getCounts(targets, only).then(v => counts[index] = v); + countPromises.push(countPromise); + } + await Promise.all(countPromises); + + const result = {counts}; + if (totalPromise !== null) { + result.total = await totalPromise; + } + return result; + } + async importDictionary(archive, progressCallback, exceptions) { this.validate(); @@ -539,4 +593,23 @@ class Database { }; }); } + + static getCounts(targets, query) { + const countPromises = []; + const counts = {}; + for (const [objectStoreName, index] of targets) { + const n = objectStoreName; + const countPromise = Database.getCount(index, query).then(count => counts[n] = count); + countPromises.push(countPromise); + } + return Promise.all(countPromises).then(() => counts); + } + + static getCount(dbIndex, query) { + return new Promise((resolve, reject) => { + const request = dbIndex.count(query); + request.onerror = (e) => reject(e); + request.onsuccess = (e) => resolve(e.target.result); + }); + } } -- cgit v1.2.3