converting to IndexedDB

This commit is contained in:
“bobbydigitales”
2023-11-12 23:31:07 -08:00
parent 6cd5a04cc1
commit 41054a5dbf
5 changed files with 240 additions and 109 deletions

View File

@@ -34,7 +34,9 @@ export function openDatabase(userID:string): Promise<IDBDatabase> {
request.onupgradeneeded = (event: IDBVersionChangeEvent) => {
const db: IDBDatabase = (event.target as IDBOpenDBRequest).result;
if (!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName, { keyPath: "id", autoIncrement: true });
let store = db.createObjectStore(storeName, { keyPath: "id", autoIncrement: true });
store.createIndex("datetimeIndex", "post_timestamp", { unique: false });
}
};
@@ -54,7 +56,7 @@ export async function addData(userID: string, data: any): Promise<void> {
const transaction = db.transaction(storeName, "readwrite");
const store = transaction.objectStore(storeName);
const addRequest = store.add(data);
const addRequest = store.add({post_timestamp: data.post_timestamp, data:data});
addRequest.onsuccess = (e: Event) => {
// console.log('Data has been added:', (e.target as IDBRequest).result);
@@ -82,7 +84,7 @@ export async function addDataArray(userID: string, array: any[]): Promise<void>
array.reverse();
for (let data of array) {
const addRequest = store.add(data);
const addRequest = store.add({post_timestamp: data.post_timestamp, data:data});
addRequest.onsuccess = (e: Event) => {
// console.log('Data has been added:', (e.target as IDBRequest).result);
};
@@ -95,9 +97,9 @@ export async function addDataArray(userID: string, array: any[]): Promise<void>
count++;
if (count % 100 === 0) {
console.log(`Added ${count} posts...`);
}
// if (count % 100 === 0) {
// console.log(`Added ${count} posts...`);
// }
}
@@ -106,7 +108,7 @@ export async function addDataArray(userID: string, array: any[]): Promise<void>
}
}
export async function getData(userID:string, lowerID:number, upperID:number): Promise<any | undefined> {
export async function getData(userID:string, lowerID:Date, upperID:Date): Promise<any | undefined> {
const storeName = `${storeNameBase}_${userID}`;
const db = await openDatabase(userID);
const transaction = db.transaction(storeName, "readonly");
@@ -117,12 +119,15 @@ export async function getData(userID:string, lowerID:number, upperID:number): Pr
const records: any[] = [];
const cursorRequest = store.openCursor(keyRangeValue);
const index = store.index("datetimeIndex");
const cursorRequest = index.openCursor(keyRangeValue);
cursorRequest.onsuccess = (event: Event) => {
const cursor = (event.target as IDBRequest).result as IDBCursorWithValue;
if (cursor) {
records.push(cursor.value); // Collect the record
records.push(cursor.value.data); // Collect the record
cursor.continue(); // Move to the next item in the range
} else {
// No more entries in the range