Skip to content

Commit 65a83cf

Browse files
committed
Initialize Express app, add PORT env fallback, harden JSON parsing, add route and start server
- Create Express app instance and use PORT from process.env with 3000 fallback. - Add try/catch around JSON.parse in array middleware and return 400 on invalid JSON. - Add POST "/" route that composes response using usernameMiddleware and arrayMiddleware. - Start server with app.listen.
1 parent 8d2a02f commit 65a83cf

1 file changed

Lines changed: 40 additions & 1 deletion

File tree

middleware-exercise/app.js

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import express from "express";
22

3+
const app = express();
4+
5+
const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
6+
37
const usernameMiddleware = (req, res, next) => {
48
const headerValue = req.get("X-username");
59

@@ -24,7 +28,13 @@ const arrayMiddleware = (req, res, next) => {
2428
req.on("end", () => {
2529
const bodyString = String.fromCharCode(...bodyBytes);
2630

27-
const bodyObject = JSON.parse(bodyString);
31+
let bodyObject;
32+
try {
33+
bodyObject = JSON.parse(bodyString);
34+
} catch (error) {
35+
res.status(400).send("Invalid JSON");
36+
return;
37+
}
2838

2939
if (
3040
Array.isArray(bodyObject) &&
@@ -41,3 +51,32 @@ const arrayMiddleware = (req, res, next) => {
4151
}
4252
});
4353
};
54+
55+
// Hey Express, whenever a POST request arrives at '/', please call this person first (usernameMiddleware), then this person (arrayMiddleware), then finally do the route logic.
56+
app.post("/", usernameMiddleware, arrayMiddleware, (req, res) => {
57+
let authPart;
58+
if (req.username) {
59+
authPart = `You are authenticated as ${req.username}`;
60+
} else {
61+
authPart = "You are not authenticated";
62+
}
63+
const MessageCount = req.body.length;
64+
65+
const messageJoined = req.body.join(",");
66+
67+
const word = MessageCount <= 1 ? "subject" : "subjects";
68+
69+
if (MessageCount > 0) {
70+
res.send(
71+
`${authPart}\n\nYou have requested information about ${MessageCount} ${word}: ${messageJoined}.`,
72+
);
73+
} else {
74+
res.send(
75+
`${authPart}\n\nYou have requested information about ${MessageCount} ${word}.`,
76+
);
77+
}
78+
});
79+
80+
app.listen(PORT, () => {
81+
console.log("Type your message here");
82+
});

0 commit comments

Comments
 (0)