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 => {