refac: @/indexed/upgrade

This commit is contained in:
2024-10-15 16:45:04 +08:00
parent 9855027876
commit 915987cbfe
4 changed files with 91 additions and 68 deletions

24
src/indexedDB/upgrade.ts Normal file
View File

@@ -0,0 +1,24 @@
import { STORAGE_NAME } from "@/const";
import { ChatStore } from "@/types/chatstore";
import { IDBPDatabase, IDBPTransaction, StoreNames } from "idb";
import { upgradeV1 } from "@/indexedDB/v1";
import { upgradeV11 } from "./v11";
export async function upgrade(
db: IDBPDatabase<ChatStore>,
oldVersion: number,
newVersion: number,
transaction: IDBPTransaction<
ChatStore,
StoreNames<ChatStore>[],
"versionchange"
>,
) {
if (oldVersion < 1) {
upgradeV1(db, oldVersion, newVersion, transaction);
}
if (oldVersion < 11) {
upgradeV11(db, oldVersion, newVersion, transaction);
}
}

38
src/indexedDB/v1.ts Normal file
View File

@@ -0,0 +1,38 @@
import { STORAGE_NAME, STORAGE_NAME_INDEXES } from "@/const";
import { ChatStore } from "@/types/chatstore";
import { IDBPDatabase, IDBPTransaction, StoreNames } from "idb";
export async function upgradeV1(
db: IDBPDatabase<ChatStore>,
oldVersion: number,
newVersion: number,
transaction: IDBPTransaction<
ChatStore,
StoreNames<ChatStore>[],
"versionchange"
>,
) {
const store = db.createObjectStore(STORAGE_NAME, {
autoIncrement: true,
});
// copy from localStorage to indexedDB
const allChatStoreIndexes: number[] = JSON.parse(
localStorage.getItem(STORAGE_NAME_INDEXES) ?? "[]",
);
let keyCount = 0;
for (const i of allChatStoreIndexes) {
console.log("importing chatStore from localStorage", i);
const key = `${STORAGE_NAME}-${i}`;
const val = localStorage.getItem(key);
if (val === null) continue;
store.add(JSON.parse(val));
keyCount += 1;
}
// setSelectedChatIndex(keyCount);
if (keyCount > 0) {
alert(
"v2.0.0 Update: Imported chat history from localStorage to indexedDB. 🎉",
);
}
}

25
src/indexedDB/v11.ts Normal file
View File

@@ -0,0 +1,25 @@
import { ChatStore } from "@/types/chatstore";
import { STORAGE_NAME } from "@/const";
import { IDBPDatabase, IDBPTransaction, StoreNames } from "idb";
export async function upgradeV11(
db: IDBPDatabase<ChatStore>,
oldVersion: number,
newVersion: number,
transaction: IDBPTransaction<
ChatStore,
StoreNames<ChatStore>[],
"versionchange"
>,
) {
if (oldVersion < 11 && oldVersion >= 1) {
alert("Start upgrading storage, just a sec... (Click OK to continue)");
}
if (
transaction
.objectStore(STORAGE_NAME)
.indexNames.contains("contents_for_index")
) {
transaction.objectStore(STORAGE_NAME).deleteIndex("contents_for_index");
}
}