connect and list usernames methods and more comments
This commit is contained in:
parent
3832413c23
commit
27ff59e174
58
index.js
58
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;
|
||||
for (const u of users)
|
||||
if (u.name === name) {
|
||||
success = false;
|
||||
break;
|
||||
// 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++);
|
||||
}
|
||||
|
||||
if (success) {
|
||||
// Change name if not taken
|
||||
// Change username
|
||||
for (const u of users)
|
||||
if (u.id === id) {
|
||||
if (consoleLogging)
|
||||
console.log(`(Re-)named user with ID '${id}'.`);
|
||||
u.name = name;
|
||||
u.name = newname;
|
||||
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);
|
||||
|
Loading…
Reference in New Issue
Block a user