From 27ff59e174a87027cb14b0b04b178f0ff47cd57a Mon Sep 17 00:00:00 2001 From: Baipyrus Date: Thu, 19 Jan 2023 15:31:14 +0100 Subject: [PATCH] connect and list usernames methods and more comments --- index.js | 68 ++++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 51 insertions(+), 17 deletions(-) diff --git a/index.js b/index.js index 02cc064..f5b57d6 100644 --- a/index.js +++ b/index.js @@ -1,6 +1,6 @@ // Global logging toggles const fileLogging = false; -const consoleLogging = true; +const consoleLogging = false; // Imports @@ -53,31 +53,41 @@ app.post('/disconnect', (req, res) => { res.status(200).send(); }); +// Check if string is already in array +function isStringUnique(arr, str) { + let match = true; + for (const s of arr) + if (s === str) { + match = false; + break; + } + return match; +} + // User wants to change name app.post('/nickname', (req, res) => { const { id, name } = req.body; - // Check if name is taken - let success = true; + // Check if name is taken, if not, append id until unique + const usernames = users.map(u => u.name); + let currentChar = 0, newname = name; + while (!isStringUnique(usernames, newname)) { + if (newname === name) + newname += '_'; + newname += id.charAt(currentChar++); + } + + // Change username for (const u of users) - if (u.name === name) { - success = false; + if (u.id === id) { + if (consoleLogging) + console.log(`(Re-)named user with ID '${id}'.`); + u.name = newname; break; } - if (success) { - // Change name if not taken - for (const u of users) - if (u.id === id) { - if (consoleLogging) - console.log(`(Re-)named user with ID '${id}'.`); - u.name = name; - break; - } - } - // Confirm renaming - res.status(200).json({ success }); + res.status(200).json({ name: newname }); }); // User is pulling messages @@ -149,6 +159,30 @@ app.post('/message', (req, res) => { res.status(200).send(); }); +// User requesting all names +app.get('/getNames', (req, res) => { + if (consoleLogging) + console.log('User requested all names.'); + + let names = [{name: "Anonymous", id: "0"}]; + for (const u of users) { + if (u.name === "") { + names[0].id = (parseInt(names[0].id) + 1).toString(); + continue; + } + names.push({ + id: u.id, + name: u.name + }); + } + if (names[0].id === "0") + names.splice(0, 1); + else + names[0].id = `${names[0].id} time(/-s)`; + + res.status(200).json(names); +}); + // Internal server error server.on('error', err => { console.error('Internal server error', err);