basic connection and naming

This commit is contained in:
Baipyrus 2023-01-17 19:15:49 +01:00
parent cd4036172d
commit 16057b4a18
2 changed files with 55 additions and 9 deletions

View File

@ -63,24 +63,43 @@ function cmd_echo(input) {
return input.join(' ');
}
function cmd_nick(input) {
if (input === undefined)
return "No nickname was given!";
user.name = input[0];
fetch('/nickname', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: user.name,
id: user.id
})
}).then(res => {});
return `Applied name '${user.name}'.`;
}
async function cmd_msg(input) {
if (input === undefined)
return "No message given!";
const data = {
id: user.id,
message: input.join(' ')
};
if (!user.connected)
return "You are not connected!";
const res = await fetch('/message', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
body: JSON.stringify({
message: input.join(' '),
id: user.id
})
});
if (res.status === 200) {
const resData = await res.json();
return resData.message;
const { message } = await res.json();
return message;
} else
return "Server returned status " + res.status;
}

View File

@ -1,4 +1,31 @@
const user = { id: crypto.randomUUID(), name: "", history: [] };
// Handle server connection
document.body.onunload = () => {
if (user.connected)
fetch('/disconnect', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: user.id
})
}).then(res => {});
};
fetch('/connect').then(res => {
if (res.status === 200) {
user.connected = true;
return res.json();
}
console.error("Could not connect to server!");
}).then(res => {
if (res === undefined)
return;
const { id } = res;
user.id = id;
});
const user = { id: "", name: "", history: [], connected: false };
let pretext = "root@baipyr.us:~# ";
// Initiating variables