Skip to content

Commit 01785a2

Browse files
committed
comments removed
1 parent 32f1b52 commit 01785a2

File tree

2 files changed

+12
-110
lines changed

2 files changed

+12
-110
lines changed

sprint3 prep tasks/serverWEBSCOKETNOTES.mjs renamed to sprint3 prep tasks/serverWEBSCOKETNOTES.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import express from "express";
22
import cors from "cors";
33
import { on } from "events";
4+
import http from "http";
45
import { server as WebSocketServer } from "websocket";
56

67
const app = express();

sprint3 prep tasks/websocket.mjs

Lines changed: 11 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -16,36 +16,16 @@ const webSocketServer = new WebSocketServer({ httpServer: server });
1616
const port = 3000;
1717
app.use(cors());
1818

19-
// npm install websocket
20-
//following this
21-
22-
//when client wants to connect to webscoket server sends a request object
2319
webSocketServer.on("request", (request) => {
24-
//call accept to open connection
25-
//accept client connection and gives connection consts to talk to client
2620
const connection = request.accept(null, request.origin);
2721

28-
//sendUTF to send text
29-
//sends msg immediately from server when connected
3022
connection.sendUTF("Hello from server");
3123

32-
//this is a listener for messages from client
3324
connection.on("message", (message) => {
3425
console.log("Msg from client", message.utf8Data);
3526
});
3627
});
3728

38-
// import express from "express";
39-
// import cors from "cors";
40-
// import { on } from "events";
41-
// import { text } from "body-parser"; issue with this so replaced with express
42-
43-
// const app = express();
44-
// const port = 3000;
45-
// because server was not working
46-
// const port = process.env.PORT || 3000;
47-
// app.use(cors());
48-
4929
const messages = [
5030
{
5131
id: 1,
@@ -57,37 +37,22 @@ const messages = [
5737
},
5838
];
5939

60-
//now with added poling since last id
61-
// from fe
62-
// const keepFetchingMessages = async () => {
63-
// const lastSeenId = messages.length > 0 ? messages[messages.length - 1].id : null;
64-
// const queryString = lastSeenId ? `?since=${lastSeenId}` : "";
65-
// const server = url
66-
// const urlofserv = `${server}messages${queryString}`;
67-
// const rawResponse = await fetch(urlofserv);
68-
// const response = await rawResponse.json();
69-
// messages.push(...response);
70-
// // render();
71-
// seeAllMessages();
72-
// setTimeout(keepFetchingMessages, 100);
73-
// }
74-
75-
// });
40+
const getRecentMessages = (sinceTime) => {
41+
return messages.filter((msg) => msg.timestamp > sinceTime);
42+
};
43+
7644
//get all messages
7745
app.get("/", (req, res) => {
7846
res.json(messages);
7947
});
8048

8149
//get recent messages poll
8250
app.get("/messages", (req, res) => {
83-
//sincetimestapm Teach your backend how to answer “since when” queries.
84-
const since = parseInt(req.query.since);
8551
if (since) {
86-
const onlyRecentMsgs = messages.filter((msg) => msg.timestamp > since);
52+
const onlyRecentMsgs = getRecentMessages(since);
8753
res.json(onlyRecentMsgs);
8854
return;
8955
}
90-
//keep if no since and show all
9156
res.json(messages);
9257
});
9358

@@ -96,23 +61,18 @@ const callbacksForNewMessages = [];
9661
app.get("/long-poll", (req, res) => {
9762
let messagesToSend = [];
9863

99-
//since from messages get
10064
const since = parseInt(req.query.since);
10165
if (since) {
102-
messagesToSend = messages.filter((msg) => msg.timestamp > since);
66+
messagesToSend = getRecentMessages(since);
10367
}
10468

105-
//from coursework pasted
106-
// Now, if 'since' was provided but no NEW messages were found,
107-
// messagesToSend.length will be 0, and the server will WAIT.
10869
if (messagesToSend.length === 0) {
10970
callbacksForNewMessages.push((value) => res.send(value));
11071
} else {
11172
res.send(messagesToSend);
11273
}
11374
});
11475

115-
//add msg to chat
11676
app.post("/", (req, res) => {
11777
const bodyBytes = [];
11878
req.on("data", (chunk) => bodyBytes.push(...chunk));
@@ -141,7 +101,6 @@ app.post("/", (req, res) => {
141101
);
142102
return;
143103
}
144-
//here add the checks on backedn 400
145104

146105
body.msgText = body.msgText.trim().replace(/[^a-zA-Z0-9,.;:?! ]/g, "");
147106
body.username = body.username.trim().replace(/[^a-zA-Z0-9,.;:?! ]/g, "");
@@ -151,7 +110,7 @@ app.post("/", (req, res) => {
151110
return;
152111
}
153112

154-
if (body.msgText.length > 400 || body.username.length > 40) {
113+
if (body.msgText.length > 400 || body.username.length >= 40) {
155114
res
156115
.status(400)
157116
.send(
@@ -198,75 +157,22 @@ app.post("/vote", (req, res) => {
198157
res.status(400).send("Expected body to be JSON.");
199158
return;
200159
}
201-
if (
202-
typeof body != "object" ||
203-
// !("username" in body) ||
204-
// !("msgText" in body)
205-
//getting by id and vote type
206-
!("id" in body) ||
207-
!("vote" in body)
208-
) {
209-
console.error(
210-
// `Failed to extract username and message text from body: ${bodyString}`
211-
`Failed to extract id and vote type.`
212-
);
160+
if (typeof body != "object" || !("id" in body) || !("vote" in body)) {
161+
console.error(`Failed to extract id and vote type.`);
213162
res
214163
.status(400)
215164
.send(
216165
"Expected body to be a JSON object containing keys uis and vote type."
217166
);
218167
return;
219168
}
220-
//this part is post new message only
221-
222-
// body.msgText = body.msgText.trim().replace(/[^a-zA-Z0-9,.;:?! ]/g, "");
223-
// body.username = body.username.trim().replace(/[^a-zA-Z0-9,.;:?! ]/g, "");
224-
225-
// if (!body.msgText || !body.username) {
226-
// res.status(400).send("Please add a quote and an username.");
227-
// return;
228-
// }
229-
230-
// if (body.msgText.length > 400 || body.username.length > 40) {
231-
// res
232-
// .status(400)
233-
// .send(
234-
// "Message text must be up to 400 chars and username must be less than 40 chars."
235-
// );
236-
// return;
237-
// }
238-
239-
// // to add new id to message
240-
// const newId = messages.length + 1;
241-
242-
// //add likes and dislikes
243-
244-
// const newMessage = {
245-
// id: newId,
246-
// msgText: body.msgText,
247-
// username: body.username,
248-
// timestamp: Date.now(),
249-
// //updated initialised
250-
// likesCount: 0,
251-
// dislikesCount: 0,
252-
// };
253-
254-
// messages.push(newMessage);
255-
256-
// while (callbacksForNewMessages.length > 0) {
257-
// const callback = callbacksForNewMessages.pop();
258-
// callback([newMessage]);
259-
// }
260-
261-
//grab currently liked disliked message
262169

263170
//add like and dislike
264171
const likeOrDislike = () => {
265172
for (const message of messages) {
266173
if (message.id === body.id) {
267174
return message;
268175
}
269-
// } return "No message with this id"; bug wrong because returns string and 404 doesnt show
270176
}
271177
return null;
272178
};
@@ -289,23 +195,18 @@ app.post("/vote", (req, res) => {
289195
return;
290196
}
291197

292-
//copy from the other post to update
293198
while (callbacksForNewMessages.length > 0) {
294199
const callback = callbacksForNewMessages.pop();
295-
// callback([newMessage]);
296200
callback([currentyLikedDislikedMsg]);
297201
}
298202

299-
// res.send("ok"); // this is wrong and message instead
300203
res.json(currentyLikedDislikedMsg);
301204
});
302205
});
303206

304-
// this was not working with websocket
305-
207+
// this was not working with websocket so the first line is changed to server listening
306208
// app.listen(port, () => {
307-
// console.error(`Chat server listening on port ${port}`);
308-
// });
209+
309210
server.listen(port, () => {
310211
console.log(`Server running at http://localhost:${port}`);
311212
});

0 commit comments

Comments
 (0)