first message prototype

This commit is contained in:
Baipyrus 2023-01-18 14:35:18 +01:00
parent 2515618d9e
commit ee6b66895c

View File

@ -1,4 +1,4 @@
const logging = true;
const logging = false;
const fs = require('fs');
const http = require('http');
@ -18,7 +18,7 @@ app.get('/connect', (req, res) => {
users.push({
socket: req.socket,
date: new Date(),
chats: [],
chats: {},
name: "",
id
});
@ -53,7 +53,7 @@ app.post('/nickname', (req, res) => {
for (const u of users)
if (u.id === id) {
if (logging)
console.log(`(Re-)named user with ID '${id}'!`);
console.log(`(Re-)named user with ID '${id}'.`);
u.name = name;
break;
}
@ -62,20 +62,9 @@ app.post('/nickname', (req, res) => {
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('/getChat', (req, res) => {
const { id } = req.body
app.post('/message', (req, res) => {
const { id, message } = req.body;
let name = "";
for (const u of users)
if (u.id === id) {
@ -83,14 +72,49 @@ app.post('/message', (req, res) => {
break;
}
let user = `User '${name}'`;
if (!name)
user = name = "Anonymous"
if (logging) {
const idStr = (!name) ? ` ID: ${id}.` : '';
console.log(`${user} sent message '${message}'.${idStr}`);
if (name === "") {
res.status(401).send();
return;
}
let chats = {};
for (const u of users)
if (name in u.chats) {
const len = u.chats[name].length;
if (len > 0)
chats[u.name] = u.chats[name].splice(0, len);
}
if (Object.keys(chats).length === 0) {
res.status(100).send();
return;
}
if (logging)
console.log(`Delivered messages to user with ID '${id}'.`);
res.status(200).json(chats);
});
app.post('/message', (req, res) => {
const { id, message, name } = req.body;
let ownName;
for (const u of users)
if (u.id === id) {
ownName = u.name;
if (!u.chats[name])
u.chats[name] = [];
u.chats[name].push(message);
break;
}
let user = `User '${ownName}'`;
if (!ownName)
user = ownName = "Anonymous"
if (logging) {
const idStr = (!ownName) ? ` ID: ${id}.` : '';
console.log(`${user} sent message '${message}'.${idStr}`);
}
res.status(200).send();
});