]> git.cworth.org Git - zombocom-ai/blobdiff - index.js
Add empty comments array when creating a new image
[zombocom-ai] / index.js
index 4108ebc2c1a3e35fac22d93079b07fc1b4608f60..b0e7d7ae4126428d383ddd31731f09feda8a570a 100644 (file)
--- a/index.js
+++ b/index.js
@@ -89,11 +89,24 @@ io.on('connection', (socket) => {
 
     // When any client comments, send that to all clients (including sender)
     socket.on('comment', (comment) => {
+        const images = state.images;
+
+        // Send comment to clients after adding commenter's name
         comment.name = socket.request.session.name;
         io.emit('comment', comment);
-        image = state.images.find(image => image.id == comment.image_id);
+
+        const index = images.findIndex(image => image.id == comment.image_id);
+
+        // Before adding the comment to server's state, drop the image_id
         delete comment.image_id;
+
+        // Now add the comment to the image, remove the image from the
+        // images array and then add it back at the end, (so it appears
+        // as the most-recently-modified image for any new clients)
+        const image = images[index];
         image.comments.push(comment);
+        images.splice(index, 1);
+        images.push(image);
     });
 
     // Generate an image when requested
@@ -111,6 +124,7 @@ io.on('connection', (socket) => {
                 const images = JSON.parse(data);
                 images.forEach((image) => {
                     image.id = state.images.length;
+                   image.comments = [];
                     io.emit('image', image);
                     state.images.push(image);
                 });