1 | /*
|
2 | Copyright 2019 New Vector Ltd
|
3 |
|
4 | Licensed under the Apache License, Version 2.0 (the "License");
|
5 | you may not use this file except in compliance with the License.
|
6 | You may obtain a copy of the License at
|
7 |
|
8 | http://www.apache.org/licenses/LICENSE-2.0
|
9 |
|
10 | Unless required by applicable law or agreed to in writing, software
|
11 | distributed under the License is distributed on an "AS IS" BASIS,
|
12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 | See the License for the specific language governing permissions and
|
14 | limitations under the License.
|
15 | */
|
16 |
|
17 | /**
|
18 | * Check if an IndexedDB database exists. The only way to do so is to try opening it, so
|
19 | * we do that and then delete it did not exist before.
|
20 | *
|
21 | * @param {Object} indexedDB The `indexedDB` interface
|
22 | * @param {string} dbName The database name to test for
|
23 | * @returns {boolean} Whether the database exists
|
24 | */
|
25 | export function exists(indexedDB, dbName) {
|
26 | return new Promise((resolve, reject) => {
|
27 | let exists = true;
|
28 | const req = indexedDB.open(dbName);
|
29 | req.onupgradeneeded = () => {
|
30 | // Since we did not provide an explicit version when opening, this event
|
31 | // should only fire if the DB did not exist before at any version.
|
32 | exists = false;
|
33 | };
|
34 | req.onblocked = () => reject();
|
35 | req.onsuccess = () => {
|
36 | const db = req.result;
|
37 | db.close();
|
38 | if (!exists) {
|
39 | // The DB did not exist before, but has been created as part of this
|
40 | // existence check. Delete it now to restore previous state. Delete can
|
41 | // actually take a while to complete in some browsers, so don't wait for
|
42 | // it. This won't block future open calls that a store might issue next to
|
43 | // properly set up the DB.
|
44 | indexedDB.deleteDatabase(dbName);
|
45 | }
|
46 | resolve(exists);
|
47 | };
|
48 | req.onerror = ev => reject(ev.target.error);
|
49 | });
|
50 | }
|