IndexedDB完全に理解した
ファイルを行き来するのが面倒なのでHTMLには余計な物を何も書いてない
code:index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script defer src=a.js></script>
<title></title>
</head>
<body>
</body>
</html>
JavaScript部分はdeno bundleで作った。基点はこれ
code:a.ts
/// <reference no-default-lib="true" />
/// <reference lib="esnext" />
/// <reference lib="dom" />
import * as idb from "./idb.ts";
document.body.innerHTML =
'<textarea id=getarea>test</textarea><textarea id=putarea>{"id": "test", "value": 42}</textarea><button id=get>get</button><button id=put>put</button>';
document.getElementById("get")!.onclick = async () => {
const textarea = document.getElementById("getarea") as HTMLTextAreaElement;
const db = await idb.open("hoge", 1, (db) => {
db.createObjectStore("hoge", { keyPath: "id" });
});
alert(JSON.stringify(await idb.get(db, "hoge", textarea.value)));
};
document.getElementById("put")!.onclick = async () => {
const textarea = document.getElementById("putarea") as HTMLTextAreaElement;
const db = await idb.open("hoge", 1, (db) => {
db.createObjectStore("hoge", { keyPath: "id" });
});
await idb.put(db, "hoge", JSON.parse(textarea.value));
alert("done");
};
IndexedDBをPromiseで扱う雑ライブラリも用意
code:idb.ts
/// <reference no-default-lib="true" />
/// <reference lib="esnext" />
/// <reference lib="dom" />
export function open(
name: string,
version = 1,
upgrade?: (db: IDBDatabase) => void,
): Promise<IDBDatabase> {
const request = indexedDB.open(name, version);
return new Promise<IDBDatabase>((resolve, reject) => {
request.onsuccess = (event) => {
// deno-lint-ignore no-explicit-any
resolve((event as any).target.result);
};
request.onerror = () => reject();
request.onupgradeneeded = (event) => {
// deno-lint-ignore no-explicit-any
upgrade?.((event as any).target.result);
};
});
}
export function get(db: IDBDatabase, storeName: string, key: string): Promise<unknown> {
const transaction = db.transaction(storeName); const store = transaction.objectStore(storeName);
return new Promise((resolve, reject) => {
const request = store.get(key);
request.onsuccess = () => resolve(request.result);
request.onerror = reject;
});
}
export function put(
db: IDBDatabase,
storeName: string,
...objects: Record<string, unknown>[]
) {
const transaction = db.transaction(storeName, "readwrite"); const store = transaction.objectStore(storeName);
return Promise.all(objects.map((obj) =>
new Promise((resolve, reject) => {
const request = store.put(obj);
request.onsuccess = resolve;
request.onerror = reject;
})
));
}