|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2022 Google LLC |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * Store db open promises for each db name/version combo to prevent |
| 20 | + * multiple attempts at opening the same db. |
| 21 | + */ |
| 22 | +const dbPromises: Record<string, Promise<IDBDatabase>> = {}; |
| 23 | + |
| 24 | +export function openDB( |
| 25 | + dbName: string, |
| 26 | + dbVersion: number, |
| 27 | + upgradeCallback: (event: IDBVersionChangeEvent) => void |
| 28 | +): Promise<IDBDatabase> { |
| 29 | + const dbPromiseKey = dbName + dbVersion; |
| 30 | + if (dbPromises[dbPromiseKey] != null) { |
| 31 | + return dbPromises[dbPromiseKey]; |
| 32 | + } |
| 33 | + dbPromises[dbPromiseKey] = new Promise((resolve, reject) => { |
| 34 | + try { |
| 35 | + const request = indexedDB.open(dbName, dbVersion); |
| 36 | + |
| 37 | + request.onsuccess = event => { |
| 38 | + resolve((event.target as IDBOpenDBRequest).result); |
| 39 | + }; |
| 40 | + |
| 41 | + request.onerror = event => { |
| 42 | + reject( |
| 43 | + `Error opening indexedDB: ${ |
| 44 | + (event.target as IDBRequest).error?.message |
| 45 | + }` |
| 46 | + ); |
| 47 | + }; |
| 48 | + |
| 49 | + request.onupgradeneeded = event => { |
| 50 | + upgradeCallback(event); |
| 51 | + }; |
| 52 | + } catch (e) { |
| 53 | + reject(`Error opening indexedDB: ${e.message}`); |
| 54 | + } |
| 55 | + }); |
| 56 | + return dbPromises[dbPromiseKey]; |
| 57 | +} |
| 58 | + |
| 59 | +export async function deleteDB(dbName: string): Promise<void> { |
| 60 | + return new Promise((resolve, reject) => { |
| 61 | + try { |
| 62 | + const request = indexedDB.deleteDatabase(dbName); |
| 63 | + |
| 64 | + request.onsuccess = () => { |
| 65 | + resolve(); |
| 66 | + }; |
| 67 | + |
| 68 | + request.onerror = event => { |
| 69 | + reject( |
| 70 | + `Error deleting indexedDB database "${dbName}": ${ |
| 71 | + (event.target as IDBRequest).error?.message |
| 72 | + }` |
| 73 | + ); |
| 74 | + }; |
| 75 | + } catch (e) { |
| 76 | + reject(`Error deleting indexedDB database "${dbName}": ${e.message}`); |
| 77 | + } |
| 78 | + }); |
| 79 | +} |
0 commit comments