Skip to content

Commit 4c90a04

Browse files
committed
Add Express middleware exercise using built-in middleware
1 parent 4d84787 commit 4c90a04

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import express from "express";
2+
3+
const app = express();
4+
const PORT = 3000;
5+
6+
// Middleware 1: Extract username from X-Username header
7+
function extractUsername(req, res, next) {
8+
const username = req.headers["x-username"];
9+
req.username = username || null;
10+
next();
11+
}
12+
13+
// Use built-in Express JSON middleware instead of custom one
14+
app.use(extractUsername);
15+
app.use(express.json());
16+
17+
app.post("/", (req, res) => {
18+
// Validate that body is an array
19+
if (!Array.isArray(req.body)) {
20+
return res.status(400).send("Request body must be a JSON array");
21+
}
22+
23+
// Check if all elements are strings
24+
const allStrings = req.body.every((item) => typeof item === "string");
25+
if (!allStrings) {
26+
return res.status(400).send("All array elements must be strings");
27+
}
28+
29+
const authMessage = req.username
30+
? `You are authenticated as ${req.username}.`
31+
: "You are not authenticated.";
32+
33+
const count = req.body.length;
34+
let subjectsMessage;
35+
if (count === 0) {
36+
subjectsMessage = "You have requested information about 0 subjects.";
37+
} else if (count === 1) {
38+
subjectsMessage = `You have requested information about 1 subject: ${req.body[0]}.`;
39+
} else {
40+
subjectsMessage = `You have requested information about ${count} subjects: ${req.body.join(
41+
", "
42+
)}.`;
43+
}
44+
45+
res.send(`${authMessage}\n\n${subjectsMessage}\n`);
46+
});
47+
48+
app.listen(PORT, () => {
49+
console.log(`Server running on http://localhost:${PORT}`);
50+
});

0 commit comments

Comments
 (0)