Files
desktop/app/providers/DialogProvider/useDialogsCache.ts
rosetta 83f38dc63f 'init'
2026-01-30 05:01:05 +02:00

69 lines
2.2 KiB
TypeScript

import { useMemory } from "../MemoryProvider/useMemory";
import { Message } from "./DialogProvider";
export interface DialogCache {
publicKey: string;
messages: Message[];
}
export function useDialogsCache() {
const [dialogsCache, setDialogsCache] = useMemory<DialogCache[]>("dialogs-cache", [], true);
const getDialogCache = (publicKey: string) => {
const found = dialogsCache.find((cache) => cache.publicKey == publicKey);
if(!found){
return [];
}
return found.messages;
}
const addOrUpdateDialogCache = (publicKey: string, messages: Message[]) => {
const existingIndex = dialogsCache.findIndex((cache) => cache.publicKey == publicKey);
let newCache = [...dialogsCache];
if(existingIndex !== -1){
newCache[existingIndex].messages = messages;
}else{
newCache.push({publicKey, messages});
}
setDialogsCache(newCache);
}
const updateAttachmentInDialogCache = (attachment_id: string, blob: string) => {
/**
* TODO: Optimize this function to avoid full map if possible
*/
let newCache = dialogsCache.map((cache) => {
let newMessages = cache.messages.map((message) => {
if(message.attachments){
let newAttachments = message.attachments.map((attachment) => {
if(attachment.id == attachment_id){
return {
...attachment,
blob: blob
}
}
return attachment;
});
return {
...message,
attachments: newAttachments
}
}
return message;
});
return {
...cache,
messages: newMessages
}
});
setDialogsCache(newCache);
}
return {
getDialogCache,
addOrUpdateDialogCache,
dialogsCache,
updateAttachmentInDialogCache,
setDialogsCache
}
}