Skip to content

Commit 474cc24

Browse files
committed
added files
1 parent f7ed68f commit 474cc24

597 files changed

Lines changed: 63473 additions & 0 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

chat-app/backend/app.js

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import express from "express";
2+
import cors from "cors";
3+
4+
const app = express();
5+
app.use(cors({
6+
origin: "https://tzemingho-chatapp-server-frontend.hosting.codeyourfuture.io"
7+
}));
8+
app.use(express.json());
9+
const port = 4000;
10+
11+
const waitingRoom = [];
12+
13+
const chatHistory = [
14+
{
15+
message: "Welcome to the channel.",
16+
user: "System",
17+
timestamp: new Date().getTime(),
18+
},
19+
];
20+
21+
app.get("/", (req, res) => {
22+
res.json(chatHistory);
23+
});
24+
25+
app.get("/messages", (req, res) => {
26+
const since = parseInt(req.query.since);
27+
28+
if (isNaN(since)) {
29+
return res.json(chatHistory);
30+
}
31+
const newMessages = chatHistory.filter(({timestamp}) => timestamp > since);
32+
33+
if (newMessages.length > 0) {
34+
return res.json(newMessages);
35+
}
36+
37+
const callback = (message) => res.json([message])
38+
waitingRoom.push(callback);
39+
40+
const seconds = 25;
41+
const miliseconds = 1000;
42+
43+
const timeout = setTimeout(() => {
44+
const index = waitingRoom.indexOf(callback);
45+
if (index !== -1) {
46+
waitingRoom.splice(index, 1)
47+
res.send([])
48+
}
49+
}, seconds * miliseconds)
50+
})
51+
52+
app.post("/", (req, res) => {
53+
try {
54+
let { message, user, timestamp } = req.body;
55+
if (!message?.trim() || !user?.trim()) {
56+
res.status(406).json({ error: "Empty message or user are not allowed." });
57+
return;
58+
} else {
59+
const newMessage = {
60+
message: message,
61+
user: user,
62+
timestamp: timestamp
63+
}
64+
chatHistory.push(newMessage);
65+
66+
while(waitingRoom.length > 0) {
67+
const callback = waitingRoom.pop();
68+
callback(newMessage);
69+
}
70+
res.status(201).send("sent");
71+
}
72+
} catch (error) {
73+
console.error(`Failed to parse body as JSON: ${error}`);
74+
res.status(400).json({ error: "Expected body to be JSON." });
75+
return;
76+
}
77+
});
78+
79+
app.listen(port, () => {
80+
console.log(`chatApp server is listening on port: ${port}`);
81+
});

0 commit comments

Comments
 (0)