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