hawk / time-arrows / files / public / db.js
Branch time-arrows · default branch · all branches
db.js
6e3f55a5 2023-10-13 Pavel Safronov | 1 | async function openDb() { |
| 2 | const promise = new Promise((resolve, reject) => { | |
| 3 | const openRequest = indexedDB.open("hawkDb", 1); | |
| 4 | ||
| 5 | openRequest.onupgradeneeded = function (e) { | |
| 6 | const db = e.target.result; | |
| 7 | if (!db.objectStoreNames.contains("spotify")) { | |
| 8 | db.createObjectStore("spotify"); | |
| 9 | } | |
| 10 | }; | |
| 11 | ||
| 12 | openRequest.onsuccess = function (e) { | |
| 13 | const db = e.target.result; | |
| 14 | resolve(db); | |
| 15 | }; | |
| 16 | ||
| 17 | openRequest.onerror = function (e) { | |
| 18 | console.error("Error opening IndexedDB:", e); | |
| 19 | reject(e); | |
| 20 | }; | |
| 21 | }); | |
| 22 | const db = await promise; | |
| 23 | return db; | |
| 24 | } | |
| 25 | ||
| 26 | async function deleteDb() { | |
| 27 | const promise = new Promise((resolve, reject) => { | |
| 28 | const deleteRequest = indexedDB.deleteDatabase("hawkDb"); | |
| 29 | ||
| 30 | deleteRequest.onsuccess = function (e) { | |
| 31 | resolve(); | |
| 32 | }; | |
| 33 | ||
| 34 | deleteRequest.onerror = function (e) { | |
| 35 | console.error("Error deleting IndexedDB:", e); | |
| 36 | reject(e); | |
| 37 | }; | |
| 38 | }); | |
| 39 | await promise; | |
| 40 | } | |
| 41 | ||
| 42 | async function setWithExpiry(db, key, value, ttl) { | |
| 43 | const item = { | |
| 44 | value: value, | |
| 45 | expiry: Date.now() + ttl | |
| 46 | }; | |
| 47 | const transaction = db.transaction("spotify", "readwrite"); | |
| 48 | const store = transaction.objectStore("spotify"); | |
| 49 | store.put(item, key); | |
| 50 | await transaction.complete; | |
| 51 | } | |
| 52 | ||
| 53 | async function getWithExpiry(db, key) { | |
| 54 | const transaction = db.transaction("spotify", "readonly"); | |
| 55 | const store = transaction.objectStore("spotify"); | |
| 56 | const promise = new Promise((resolve, reject) => { | |
| 57 | const request = store.get(key); | |
| 58 | request.onsuccess = function (e) { | |
| 59 | resolve(e.target.result); | |
| 60 | }; | |
| 61 | request.onerror = function (e) { | |
| 62 | console.error("Error getting from IndexedDB:", e); | |
| 63 | reject(e); | |
| 64 | }; | |
| 65 | }); | |
| 66 | const item = await promise; | |
| 67 | if (!item) { | |
| 68 | return null; | |
| 69 | } | |
| 70 | console.debug(`Cache hit for ${key}`); | |
| 71 | console.debug(JSON.stringify(item)) | |
| 72 | console.debug(item) | |
| 73 | ||
| 74 | if (!item) { | |
| 75 | return null; | |
| 76 | } | |
| 77 | if (Date.now() > item.expiry) { | |
| 78 | return null; | |
| 79 | } | |
| 80 | return item.value; | |
| 81 | } |