From 1cc6597bbdff00d6355c83069edb891cefa57c28 Mon Sep 17 00:00:00 2001
From: Carl Worth <cworth@cworth.org>
Date: Tue, 6 Dec 2022 21:21:29 -0800
Subject: [PATCH] Add peristence of comments

The server saves every message it receives, and replays them to each
new client when it joins.

Note: The server is only holding messages in memory, so there's not
yet any persistence across server restarts.
---
 index.js | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/index.js b/index.js
index 27b3714..80526a3 100644
--- a/index.js
+++ b/index.js
@@ -6,13 +6,21 @@ const { Server } = require("socket.io");
 const io = new Server(server);
 const port = 2122;
 
+comments = [];
+
 app.get('/index.html', (req, res) => {
     res.sendFile(__dirname + '/index.html');
 });
 
 io.on('connection', (socket) => {
-    socket.on('comment', (msg) => {
-        io.emit('comment', msg);
+    // Replay old comments to a newly-joining client
+    comments.forEach((comment) => {
+        socket.emit('comment', comment)
+    });
+    // When any client comments, send that to all clients (including sender)
+    socket.on('comment', (comment) => {
+        io.emit('comment', comment);
+        comments.push(comment);
     });
 });
 
-- 
2.45.2