Skip to content

Commit 810039b

Browse files
committed
Add Sprint 3 task: custom middleware version
1 parent c977d8d commit 810039b

6 files changed

Lines changed: 911 additions & 0 deletions

File tree

middleware-custom/.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules

middleware-custom/app.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import express from "express";
2+
import usernameMiddleware from "./middleware/usernameMiddleware.js";
3+
import jsonArrayMiddleware from "./middleware/jsonArrayMiddleware.js";
4+
5+
const app = express();
6+
7+
// POST route using both the JSON body parser and the username middleware
8+
app.post("/", usernameMiddleware, jsonArrayMiddleware, (req, res) => {
9+
const username = req.username;
10+
const subjects = req.jsonArray;
11+
12+
const authMessage = username
13+
? `You are authenticated as ${username}!`
14+
: "You are not authenticated.";
15+
16+
const count = subjects.length;
17+
const list = subjects.join(", ");
18+
19+
let subjectMessage;
20+
if (count === 0) {
21+
subjectMessage = "You have no subjects.";
22+
} else if (count === 1) {
23+
subjectMessage = `You have 1 subject: ${list}.`;
24+
} else {
25+
subjectMessage = `You have ${count} subjects: ${list}.`;
26+
}
27+
res.send(`${authMessage} ${subjectMessage}`);
28+
});
29+
30+
app.listen(3000, () => {
31+
console.log("Server is running on port 3000");
32+
});
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
export default function jsonArrayMiddleware(req, res, next) {
2+
let data = "";
3+
4+
req.on("data", (chunk) => {
5+
data += chunk.toString();
6+
});
7+
8+
req.on("end", () => {
9+
try {
10+
const parsedData = JSON.parse(data);
11+
12+
if (!Array.isArray(parsedData)) {
13+
return res.status(400).send("Expected an array in the request body");
14+
}
15+
const allStrings = parsedData.every((item) => typeof item === "string");
16+
17+
if (!allStrings) {
18+
return res.status(400).send("All items in the array must be strings");
19+
}
20+
21+
req.jsonArray = parsedData;
22+
next();
23+
} catch (err) {
24+
console.error("Error parsing JSON:", err);
25+
res.status(400).send("Invalid JSON format");
26+
}
27+
});
28+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
export default function usernameMiddleware(req, res, next) {
2+
const username = req.headers["x-username"];
3+
4+
req.username = username ?? null;
5+
6+
next();
7+
}

0 commit comments

Comments
 (0)