Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions chat-server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { fileURLToPath } from "url";

const app = express();

app.use(express.json());
app.use(cors());

// Get __dirname in ES module
Expand All @@ -25,6 +26,31 @@ app.get("/", (request, response) => {
response.sendFile(__dirname + "/index.html");
});

app.post("/messages", (req, res) => {
const newMessage = req.body;
messages.push(newMessage);
Copy link

@garydev10 garydev10 Apr 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good grasp of Create (POST) function!
However, does reg.body contain all properties required in the message? (See Data Model)

res.send("Message added");
});

app.get("/messages", (req, res) => {
res.send(messages);
});

app.get("/messages/:id", (req, res) => {
const messageId = parseInt(req.params.id);
const message = messages.find((obj) => obj.id === messageId );
if (!message) return res.status(404).json({ message: "Message does not exist" });

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even though your code here is correct and works, a lot of programmers will always add {}s around if bodies, even if they're just one statement - have a read of https://www.synopsys.com/blogs/software-security/understanding-apple-goto-fail-vulnerability-2.html for some explanation as to why :)

res.json(message);
});

app.delete("/messages/:id", (req, res) => {
const index = messages.findIndex((obj) => obj.id === parseInt(req.params.id));
if (index === -1) return res.status(404).json({ message: "No message to delete" });

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even though your code here is correct and works, a lot of programmers will always add {}s around if bodies, even if they're just one statement - have a read of https://www.synopsys.com/blogs/software-security/understanding-apple-goto-fail-vulnerability-2.html for some explanation as to why :)


messages.splice(index, 1);
res.json({message : "Message successfully deleted"});
})

app.listen(process.env.PORT, () => {
console.log(`listening on PORT ${process.env.PORT}...`);
});