connect and list usernames methods and more comments

This commit is contained in:
Baipyrus 2023-01-19 15:31:14 +01:00
parent 3832413c23
commit 27ff59e174

View File

@ -1,6 +1,6 @@
// Global logging toggles // Global logging toggles
const fileLogging = false; const fileLogging = false;
const consoleLogging = true; const consoleLogging = false;
// Imports // Imports
@ -53,31 +53,41 @@ app.post('/disconnect', (req, res) => {
res.status(200).send(); 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 // User wants to change name
app.post('/nickname', (req, res) => { app.post('/nickname', (req, res) => {
const { id, name } = req.body; const { id, name } = req.body;
// Check if name is taken // Check if name is taken, if not, append id until unique
let success = true; const usernames = users.map(u => u.name);
for (const u of users) let currentChar = 0, newname = name;
if (u.name === name) { while (!isStringUnique(usernames, newname)) {
success = false; if (newname === name)
break; newname += '_';
newname += id.charAt(currentChar++);
} }
if (success) { // Change username
// Change name if not taken
for (const u of users) for (const u of users)
if (u.id === id) { if (u.id === id) {
if (consoleLogging) if (consoleLogging)
console.log(`(Re-)named user with ID '${id}'.`); console.log(`(Re-)named user with ID '${id}'.`);
u.name = name; u.name = newname;
break; break;
} }
}
// Confirm renaming // Confirm renaming
res.status(200).json({ success }); res.status(200).json({ name: newname });
}); });
// User is pulling messages // User is pulling messages
@ -149,6 +159,30 @@ app.post('/message', (req, res) => {
res.status(200).send(); 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 // Internal server error
server.on('error', err => { server.on('error', err => {
console.error('Internal server error', err); console.error('Internal server error', err);