1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
|
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
class DatabaseUtils {
/** Wrap an IndexedDB request into a Promise.
*
* This should not be used for open().
*
* @param {IDBRequest} request the request to be wrapped
* @returns {Promise<Object>} promise that resolves with the request's result,
* or rejects with an error
*/
static async promiseForRequest(request) {
return new Promise((resolve, reject) => {
request.onsuccess = event => { resolve(event.target.result); };
request.onerror = event => { reject(event.target.error); };
request.onblocked = event => {
reject(event.target.error ||
(new Error("blocked by other database connections")));
};
request.onupgradeneeded = event => {
reject(event.target.error ||
(new Error("unexpected upgradeneeded event")));
};
});
}
/** Wrap an IndexedDB database open request into a Promise.
*
* This is intended to be used by open().
*
* @param {IDBOpenDBRequest} request the request to be wrapped
* @returns {Promise<{database: idbDatabase, transaction: IDBTransaction?}>}
* promise that resolves with an object whose "database" property is the
* newly opened database; if an upgradeneeded event is received, the
* "transaction" property holds the upgrade transaction
*/
static async promiseForOpenRequest(request) {
return new Promise((resolve, reject) => {
request.onsuccess = event => {
resolve({ database: event.target.result, transaction: null });
};
request.onerror = event => { reject(event.target.error); };
request.onblocked = event => {
reject(event.target.error ||
(new Error("blocked by other database connections")));
};
request.onupgradeneeded = event => {
resolve({
database: event.target.result,
transaction: event.target.transaction
});
};
});
}
/** Wrap an IndexedDB transaction into a Promise.
*
* @param {IDBTransaction} transaction the transaction to be wrapped
* @returns {Promise<Object>} promise that resolves with undefined when the
* transaction is completed, or rejects with an error if the transaction
* is aborted or errors out
*/
static async promiseForTransaction(transaction) {
return new Promise((resolve, reject) => {
transaction.oncomplete = () => { resolve(); };
transaction.onabort = event => { reject(event.target.error); };
transaction.onerror = event => { reject(event.target.error); };
});
}
}
class Database {
/** Open a database.
*
* @param {string} dbName the name of the database to be opened
* @return {Promise<Database>} promise that resolves with a new Database
* instance for the open database
*/
static async open(dbName) {
const request = indexedDB.open(dbName, 1);
const result = await DatabaseUtils.promiseForOpenRequest(request);
if (result.transaction !== null) {
fail("expected db to exist");
return;
}
return new Database(dbName, result.database);
}
/** Do not instantiate directly. Use Database.open() instead.
*
* @param {string} dbName the database's name
* @param {IDBDatabase} idbDatabase the IndexedDB instance wrapped by this
*/
constructor(dbName, idbDatabase) {
this._dbName = dbName;
this._idbDatabase = idbDatabase;
}
/** Closes the underlying database. All future operations will fail. */
close() {
this._idbDatabase.close();
}
/** Reads from a store by iterating a cursor.
*
* @param {string} storeName the name of the store being read
* @param {{index?: string, range?: IDBKeyRange}} query narrows down the data
* being read
* @param {function(IDBCursor): boolean} cursorCallback called for each cursor
* yielded by the iteration; must return a truthy value to continue
* iteration, or a falsey value to stop iterating
*/
async iterateCursor(storeName, query, cursorCallback) {
const transaction = this._idbDatabase.transaction([storeName], 'readonly');
const transactionPromise = DatabaseUtils.promiseForTransaction(transaction);
const objectStore = transaction.objectStore(storeName);
const dataSource = ('index' in query) ? objectStore.index(query.index)
: objectStore;
const request = ('range' in query) ? dataSource.openCursor(query.range)
: dataSource.openCursor();
while (true) {
const cursor = await DatabaseUtils.promiseForRequest(request);
if (!cursor)
break; // The iteration completed.
const willContinue = cursorCallback(cursor);
if (!willContinue)
break;
cursor.continue();
}
await transactionPromise;
return true;
}
async read() {
const status = document.getElementById('status');
status.textContent = 'Started reading items';
let i = 0;
const result = await this.iterateCursor('store', {}, cursor => {
i += 1;
if (cursor.primaryKey !== i) {
status.textContent =
`Incorrect primaryKey - wanted ${i} got ${cursor.primaryKey}`;
return false;
}
if (cursor.key !== i) {
status.textContent = `Incorrect key - wanted ${i} got ${cursor.key}`;
return false;
}
if (cursor.value.id !== i) {
status.textContent =
`Incorrect value.id - wanted ${i} got ${cursor.key}`;
return false;
}
return true;
});
if (!result) {
status.textContent = `Failed to read items`;
return false;
}
status.textContent = `Done reading ${i} items`;
return true;
}
};
|