From 2515618d9e35a288a751baae98d05a3b9dcd7932 Mon Sep 17 00:00:00 2001 From: Baipyrus Date: Wed, 18 Jan 2023 08:02:42 +0100 Subject: [PATCH] async print to console --- index.js | 40 +++++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/index.js b/index.js index 71f61ba..336f12c 100644 --- a/index.js +++ b/index.js @@ -18,6 +18,7 @@ app.get('/connect', (req, res) => { users.push({ socket: req.socket, date: new Date(), + chats: [], name: "", id }); @@ -40,14 +41,37 @@ app.post('/disconnect', (req, res) => { app.post('/nickname', (req, res) => { const { id, name } = req.body; + + let success = true; for (const u of users) - if (u.id === id) { - if (logging) - console.log(`(Re-)named user with ID '${id}'!`); - u.name = name; + if (u.name === name) { + success = false; break; } - res.status(200).send(); + + if (success) { + for (const u of users) + if (u.id === id) { + if (logging) + console.log(`(Re-)named user with ID '${id}'!`); + u.name = name; + break; + } + } + + res.status(200).json({ success }); +}); + +app.post('/chatInit', (req, res) => { + const { id, name } = req.body; + for (const u of users) + if (u.id === id) { + u.chats.push({ + messages: [], + name + }); + break; + } }); app.post('/message', (req, res) => { @@ -58,15 +82,17 @@ app.post('/message', (req, res) => { name = u.name; break; } + let user = `User '${name}'`; if (!name) user = name = "Anonymous" - if (logging) { const idStr = (!name) ? ` ID: ${id}.` : ''; console.log(`${user} sent message '${message}'.${idStr}`); } - res.status(200).json({ message }); + + + res.status(200).send(); }); server.on('error', err => {