Skip to content

Commit 4c084cb

Browse files
committed
switch back to localhost, and make timestamp at the backend
1 parent da4170f commit 4c084cb

2 files changed

Lines changed: 56 additions & 51 deletions

File tree

chat-app/backend/app.js

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@ import express from "express";
22
import cors from "cors";
33

44
const app = express();
5-
app.use(cors({
6-
origin: "https://tzemingho-chatapp-server-frontend.hosting.codeyourfuture.io"
7-
}));
5+
app.use(
6+
cors({
7+
// origin: "https://tzemingho-chatapp-server-frontend.hosting.codeyourfuture.io"
8+
}),
9+
);
810
app.use(express.json());
911
const port = 4000;
1012

@@ -28,45 +30,46 @@ app.get("/messages", (req, res) => {
2830
if (isNaN(since)) {
2931
return res.json(chatHistory);
3032
}
31-
const newMessages = chatHistory.filter(({timestamp}) => timestamp > since);
33+
const newMessages = chatHistory.filter(({ timestamp }) => timestamp > since);
3234

3335
if (newMessages.length > 0) {
3436
return res.json(newMessages);
3537
}
3638

37-
const callback = (message) => res.json([message])
39+
const callback = (message) => res.json([message]);
3840
waitingRoom.push(callback);
3941

4042
const seconds = 25;
41-
const miliseconds = 1000;
43+
const milliseconds = 1000;
4244

4345
const timeout = setTimeout(() => {
4446
const index = waitingRoom.indexOf(callback);
4547
if (index !== -1) {
46-
waitingRoom.splice(index, 1)
47-
res.send([])
48+
waitingRoom.splice(index, 1);
49+
res.send([]);
4850
}
49-
}, seconds * miliseconds)
50-
})
51+
}, seconds * milliseconds);
52+
});
5153

5254
app.post("/", (req, res) => {
5355
try {
54-
let { message, user, timestamp } = req.body;
56+
let { message, user } = req.body;
5557
if (!message?.trim() || !user?.trim()) {
5658
res.status(406).json({ error: "Empty message or user are not allowed." });
5759
return;
5860
} else {
61+
const newTimestamp = new Date().getTime();
5962
const newMessage = {
6063
message: message,
6164
user: user,
62-
timestamp: timestamp
63-
}
65+
timestamp: newTimestamp,
66+
};
6467
chatHistory.push(newMessage);
6568

66-
while(waitingRoom.length > 0) {
69+
while (waitingRoom.length > 0) {
6770
const callback = waitingRoom.pop();
6871
callback(newMessage);
69-
}
72+
}
7073
res.status(201).send("sent");
7174
}
7275
} catch (error) {

chat-app/frontend/scripts.js

Lines changed: 38 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
const state = {
22
messageString: "",
33
userString: "",
4-
backendURL: "https://tzemingho-chatapp-server-backend.hosting.codeyourfuture.io",
5-
// backendURL: "http://localhost:4000",
4+
// backendURL: "https://tzemingho-chatapp-server-backend.hosting.codeyourfuture.io",
5+
backendURL: "http://localhost:4000",
66
messages: [],
7-
}
8-
7+
};
98

109
function createEmptyMessage() {
1110
const emptyMessage = document.createElement("p");
@@ -38,10 +37,9 @@ function createMessageThreads(chatHistoryArray) {
3837
});
3938
}
4039

41-
4240
async function chatDisplay() {
4341
const chatDisplayArea = document.getElementById("chat-display-area");
44-
chatDisplayArea.innerHTML = '';
42+
chatDisplayArea.innerHTML = "";
4543
const chatHistoryArray = state.messages;
4644
if (chatHistoryArray.length == 0) {
4745
chatDisplayArea.append(createEmptyMessage());
@@ -51,21 +49,24 @@ async function chatDisplay() {
5149
}
5250

5351
const keepFetchingMessages = async () => {
54-
const lastMessageTime = state.messages.length > 0 ? state.messages[state.messages.length - 1].timestamp : null;
55-
const queryString = lastMessageTime ? `?since=${lastMessageTime}` : "";
56-
const url = `${state.backendURL}/messages${queryString}`;
57-
try {
58-
const rawResponse = await fetch(url);
59-
const response = await rawResponse.json();
60-
if (response.length > 0) {
61-
state.messages.push(...response);
62-
chatDisplay();
63-
}
64-
} catch (error) {
65-
console.log(`Failed on connection: ${error}`)
52+
const lastMessageTime =
53+
state.messages.length > 0
54+
? state.messages[state.messages.length - 1].timestamp
55+
: null;
56+
const queryString = lastMessageTime ? `?since=${lastMessageTime}` : "";
57+
const url = `${state.backendURL}/messages${queryString}`;
58+
try {
59+
const rawResponse = await fetch(url);
60+
const response = await rawResponse.json();
61+
if (response.length > 0) {
62+
state.messages.push(...response);
63+
chatDisplay();
6664
}
67-
setTimeout(keepFetchingMessages, 100);
68-
}
65+
} catch (error) {
66+
console.log(`Failed on connection: ${error}`);
67+
}
68+
setTimeout(keepFetchingMessages, 100);
69+
};
6970

7071
function messageInputReset() {
7172
state.messageString = "";
@@ -82,14 +83,14 @@ async function postingMessage(messageString, userString) {
8283
const response = await fetch(state.backendURL, {
8384
method: "POST",
8485
headers: {
85-
"Content-Type": "application/json"
86+
"Content-Type": "application/json",
8687
},
8788
body: JSON.stringify({
8889
message: messageString,
8990
user: userString,
90-
timestamp: newTimestamp
91-
})
92-
})
91+
timestamp: newTimestamp,
92+
}),
93+
});
9394
if (response.ok) {
9495
const confirmMessage = await response.text();
9596
if (confirmMessage == "sent") {
@@ -98,36 +99,37 @@ async function postingMessage(messageString, userString) {
9899
}
99100
}
100101
} catch (error) {
101-
console.error(`Failed to post message: ${error}`)
102+
console.error(`Failed to post message: ${error}`);
102103
}
103104
}
104105

105106
async function messageSubmitHandler(e, messageString, userString) {
106107
e.preventDefault();
107108
if (!messageString || !userString) {
108-
console.error(`Message or user cannot be empty.`)
109-
window.alert("Message or user cannot be empty.")
109+
console.error(`Message or user cannot be empty.`);
110+
window.alert("Message or user cannot be empty.");
110111
return;
111112
} else {
112-
await postingMessage(messageString, userString)
113+
await postingMessage(messageString, userString);
113114
}
114115
}
115116

116117
function messageInputHandler() {
117-
118-
const messageInputElement = document.getElementById("message-input")
118+
const messageInputElement = document.getElementById("message-input");
119119
messageInputElement.addEventListener("input", (e) => {
120120
state.messageString = e.target.value.trim();
121-
})
121+
});
122122

123-
const userInputElement = document.getElementById("user-name-input")
123+
const userInputElement = document.getElementById("user-name-input");
124124
userInputElement.addEventListener("input", (e) => {
125125
state.userString = e.target.value.trim();
126-
})
126+
});
127127

128-
document.getElementById("message-submit-button").addEventListener("click", async (e) => {
129-
await messageSubmitHandler(e, state.messageString, state.userString)
130-
})
128+
document
129+
.getElementById("message-submit-button")
130+
.addEventListener("click", async (e) => {
131+
await messageSubmitHandler(e, state.messageString, state.userString);
132+
});
131133
}
132134

133135
window.onload = async () => {

0 commit comments

Comments
 (0)