got chat working

This commit is contained in:
leca 2024-06-21 12:48:29 +03:00
parent a500916712
commit 74b3f14cbb
3 changed files with 55 additions and 28 deletions

View File

@ -86,7 +86,8 @@ wss.on('connection', function (ws, request) {
}
//Inserting a message into database.
let messageId = (await client.query("INSERT INTO Messages (author_id, time_sent, content) VALUES($1, NOW(), $2) RETURNING ID", [userId, text])).rows[0].id;
const { id, time_sent } = (await client.query("INSERT INTO Messages (author_id, time_sent, content) VALUES($1, NOW(), $2) RETURNING ID, time_sent", [userId, text])).rows[0];
let messageId = id
await client.query("UPDATE Chats SET messages = ARRAY_APPEND(messages, $1) WHERE ID = $2", [messageId, chatId])
// sessions[token].socket.send("successful");
@ -102,14 +103,15 @@ wss.on('connection', function (ws, request) {
for (const [key, value] of Object.entries(sessions)) {
let session = value;
if (session == undefined) continue
if (session.userId == userId) continue; // Skip the sender of the message
// if (session.userId == userId) continue; // Skip the sender of the message
if (Ids.includes(session.userId)) {
session.socket.send(JSON.stringify({
action: "message",
content: {
chatId: chatId,
authorId: userId,
text: text
text: text,
timeSent: time_sent
}
}));
}

View File

@ -1,8 +1,7 @@
const sendMessage = (event) => {
if (event.key == "Enter") {
console.log(event);
}
}
let socket
let header = document.getElementById('header-text');
let content = document.getElementById('content-div')
let chatId;
const createMessageElement = async (message) => {
@ -11,7 +10,7 @@ const createMessageElement = async (message) => {
let messageDiv = document.createElement("div");
messageDiv.id = `message-${message.id}`;
messageDiv.style = "background-color: gray; box-shadow: 1px 1px; margin: 10px; padding: 5px"
messageDiv.style = "background-color: gray; box-shadow: 3px 3px; margin: 10px; padding: 5px"
let authorName = document.createElement("b");
authorName.innerText = `${author.firstname}:`;
@ -29,26 +28,63 @@ const createMessageElement = async (message) => {
messageDiv.appendChild(messageTime);
return messageDiv
}
};
const sendMessage = (event) => {
if (event.key == "Enter") {
const text = event.target.value
event.target.value = ""
socket.send(JSON.stringify(
{
"action": "message",
"content": {
"chatId": chatId,
"text": text
}
}
));
}
};
window.addEventListener('load', async function () {
let connectionString = window.location.protocol == "https:" ? `wss://${window.location.hostname}:${window.location.port}` : `ws://${window.location.hostname}:${window.location.port}`
socket = new WebSocket(connectionString)
socket.addEventListener('message', async (m) => {
if (m.data == "successful") return;
const data = JSON.parse(m.data)
switch (data.action) {
case "message": {
if (data.content.chatId == chatId) {
let msg = {
author_id: data.content.authorId,
content: data.content.text,
time_sent: data.content.timeSent
}
content.appendChild(await createMessageElement(msg));
} else {
alert(`New message in chat ${data.content.chatId} from ${data.content.authorId}, which says '${data.content.text}'`)
}
break;
}
}
})
let location = window.location.href.split("/")
const chatId = location[location.length - 1];
chatId = location[location.length - 1];
let chatInfo = JSON.parse(
await fetch(`/api/getChatInfo/${chatId}`).then(response => response.text()).then(response => { return response })
);
console.log(chatInfo)
let header = document.getElementById('header-text');
header.innerText = chatInfo.name;
let content = document.getElementById('content-div')
let today = new Date();
today.setUTCDate(today.getUTCDate() + 1)
let yesterday = new Date();
yesterday.setUTCDate(today.getUTCDate() - 10);
console.log(today.toISOString(), yesterday.toISOString())
// fetching messages from yesterday to today
let messages = await fetch("/api/getMessagesFromChat/by-time", {
method: "POST",

View File

@ -3,24 +3,13 @@ let socket
window.addEventListener('load', async function () {
let connectionString = location.protocol == "https:" ? `wss://${window.location.hostname}:${window.location.port}` : `ws://${window.location.hostname}:${window.location.port}`
socket = new WebSocket(connectionString)
socket.addEventListener('open', (e) => {
socket.send(JSON.stringify(
{
"action": "message",
"content": {
"chatId": 1,
"text": "test"
}
}
));
})
socket.addEventListener('message', (m) => {
if (m.data == "successful") return;
const data = JSON.parse(m.data)
switch (data.action) {
case "message": {
console.log(`New message in chat ${data.content.chatId} from ${data.content.authorId}, which says '${data.content.text}'`)
alert(`New message in chat ${data.content.chatId} from ${data.content.authorId}, which says '${data.content.text}'`)
break;
}
}