]> Repos - mime-chat/commitdiff
add message delete on size limit
authorriqo <hernandeze2@xavier.edu>
Sat, 13 Mar 2021 16:50:33 +0000 (10:50 -0600)
committerriqo <hernandeze2@xavier.edu>
Sat, 13 Mar 2021 16:50:33 +0000 (10:50 -0600)
src/modules/messages.ts

index e3c9286327510f6300d9d40abba8d5c7c53bca0c..9becb4de04f6763bb6c0a126c512b1e4379ce8cd 100644 (file)
@@ -1,10 +1,13 @@
 import { ref } from 'vue';
 import { RenderMessage, Annotation } from "@/types/message/index";
 
-const messages = ref(new Map());
-
 const messagesKey = "CRIMATA_MESSAGES";
+const sizeLimit = 200;
+
+// list of messages where the first item is the oldest message.
+const messages = ref(new Map());
 
+// get stored messages.
 const messagesString = window.localStorage.getItem(messagesKey);
 
 if (messagesString) {
@@ -14,9 +17,22 @@ if (messagesString) {
   messages.value = new Map(Object.entries(parsed));
 }
 
+// utility function to remove oldest message from the messages map. 
+function deleteOldest() { 
+   // create array of map keys and get the key of the oldest message.
+   const lastKey = Array.from(messages.value.keys()).shift();
+
+   messages.value.delete(lastKey);
+}
+
 export default function useMessages() {
 
-    const addMessage = (m: RenderMessage) => messages.value.set(m.uid, m);
+    const addMessage = (m: RenderMessage) => {
+      // check for message limit before setting a new message.
+      if (messages.value.size >= sizeLimit) deleteOldest();
+      
+      messages.value.set(m.uid, m);
+    }
 
     const updateMessage = (m: Annotation) => {
         // update message if in the map.