-
Notifications
You must be signed in to change notification settings - Fork 8
/
indexdb.ts
43 lines (36 loc) · 1.37 KB
/
indexdb.ts
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
const dbName = "TeaTimeStorage";
const dbVersion = 1;
const storeName = "files";
function openDB(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(dbName, dbVersion);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
request.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
db.createObjectStore(storeName, { keyPath: "cid" });
};
});
}
// Save a File object and its hash
export async function saveFile(file: File, cid: string): Promise<void> {
const db = await openDB();
const transaction = db.transaction(storeName, "readwrite");
const store = transaction.objectStore(storeName);
return new Promise((resolve, reject) => {
const request = store.put({ cid, file });
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
});
}
// Lookup a File object by its hash
export async function getFile(cid: string): Promise<File | undefined> {
const db = await openDB();
const transaction = db.transaction(storeName, "readonly");
const store = transaction.objectStore(storeName);
return new Promise((resolve, reject) => {
const request = store.get(cid);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result?.file);
});
}