peers syncing for a single user
This commit is contained in:
58
src/db.ts
58
src/db.ts
@@ -4,6 +4,9 @@
|
||||
// email: string;
|
||||
// }
|
||||
|
||||
|
||||
// Efficiently storing data in indexdb: https://stackoverflow.com/a/62975917
|
||||
|
||||
const postStoreName: string = "posts";
|
||||
let keyBase = "dandelion_posts_v1_"
|
||||
let key = "";
|
||||
@@ -156,6 +159,60 @@ export async function addDataArray(userID: string, array: any[]): Promise<void>
|
||||
}
|
||||
}
|
||||
|
||||
export async function mergeDataArray(userID: string, array:any[]): Promise<void> {
|
||||
try {
|
||||
const db = await openDatabase(userID);
|
||||
const transaction = db.transaction(postStoreName, "readwrite");
|
||||
const store = transaction.objectStore(postStoreName);
|
||||
const index = store.index("postIDIndex");
|
||||
|
||||
transaction.oncomplete = () => {
|
||||
console.log("Transaction completed successfully");
|
||||
db.close();
|
||||
};
|
||||
|
||||
transaction.onerror = (event) => {
|
||||
console.error("Transaction error:", (event.target as any).error);
|
||||
db.close();
|
||||
};
|
||||
|
||||
let postsToWrite:any = [];
|
||||
|
||||
for (let post of array) {
|
||||
try {
|
||||
let havePost = await new Promise<boolean>((resolve, reject) => {
|
||||
const getRequest = index.getKey(post.post_id);
|
||||
|
||||
getRequest.onerror = (e) => {
|
||||
console.log((e.target as IDBRequest).error);
|
||||
reject(e);
|
||||
};
|
||||
|
||||
getRequest.onsuccess = async (e) => {
|
||||
const key = (e.target as IDBRequest).result;
|
||||
resolve(key !== undefined)
|
||||
};
|
||||
|
||||
});
|
||||
|
||||
// console.log(post.post_id, havePost);
|
||||
if (!havePost ) {
|
||||
postsToWrite.push(post);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error processing post:", error);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Writing ${postsToWrite.length} posts`);
|
||||
|
||||
await addDataArray(userID, postsToWrite);
|
||||
} catch (error) {
|
||||
console.error("Error in opening database:", error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getData(userID: string, lowerID: Date, upperID: Date): Promise<any | undefined> {
|
||||
const db = await openDatabase(userID);
|
||||
const transaction = db.transaction(postStoreName, "readonly");
|
||||
@@ -191,6 +248,7 @@ export async function getData(userID: string, lowerID: Date, upperID: Date): Pro
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
export async function getAllData(userID: string): Promise<any | undefined> {
|
||||
const db = await openDatabase(userID);
|
||||
const transaction = db.transaction(postStoreName, "readonly");
|
||||
|
||||
Reference in New Issue
Block a user