This repository was archived by the owner on Aug 17, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 440
Expand file tree
/
Copy pathserver.js
More file actions
66 lines (54 loc) · 1.57 KB
/
server.js
File metadata and controls
66 lines (54 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
app.use(cors());
const welcomeMessage = {
id: 0,
from: "Bart",
text: "Welcome to CYF chat system!",
};
//This array is our "data store".
//We will start with one message in the array.
//Note: messages will be lost when Glitch restarts our server.
const messages = [welcomeMessage];
app.get("/", function (request, response) {
response.sendFile(__dirname + "/index.html");
});
app.get("/messages/search", (req, res) => {
const { term } = req.query;
console.log(term);
const filterMessages = messages.filter((message) =>
message.text.toLowerCase().includes(term.toLowerCase())
);
console.log(filterMessages);
res.send(filterMessages);
});
app.get("/messages", (req, res) => {
res.json(messages);
});
app.get("/messages/:id", function (req, res) {
const id = req.params.id;
messages = messages.filter((message) => message.id === Number(id));
res.status(200).send(messages);
});
app.get("/messages/latest", (req, res) => {
res.json(messages.slice(-10));
});
app.post("/messages", (req, res) => {
const { from, text } = req.body;
const ourMessageObject = {
id: Date.now(),
from,
text,
timeSent: new Date().toLocaleDateString(),
};
messages.push(ourMessageObject);
res.send("Message received successfully.");
});
app.delete("/messages/:id", (req, res) => {
const id = req.params.id;
messages = messages.filter((message) => message.id !== Number(id));
res.json(messages);
});
app.listen(process.env.PORT);