Skip to content

Commit f829090

Browse files
committed
Refactor middleware.js file
1 parent 4c90a04 commit f829090

File tree

1 file changed

+16
-29
lines changed

1 file changed

+16
-29
lines changed

sprint3_exercises/middleware.js

Lines changed: 16 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -10,41 +10,28 @@ function extractUsername(req, res, next) {
1010
next();
1111
}
1212

13-
// Middleware 2: Parse POST body as JSON array of strings
14-
function parseJsonArrayBody(req, res, next) {
15-
let bodyString = "";
16-
17-
req.on("data", (chunk) => {
18-
bodyString += chunk;
19-
});
20-
21-
req.on("end", () => {
22-
try {
23-
const parsed = JSON.parse(bodyString);
24-
25-
// Check if it's an array
26-
if (!Array.isArray(parsed)) {
27-
return res.status(400).send("Request body must be a JSON array");
28-
}
13+
// Middleware 2: Parse POST body as JSON (reusable for any JSON parsing)
14+
app.use(express.json());
15+
16+
// Middleware 3: Validate that body is an array of strings
17+
function validateArrayOfStrings(req, res, next) {
18+
// Check if it's an array
19+
if (!Array.isArray(req.body)) {
20+
return res.status(400).send("Request body must be a JSON array");
21+
}
2922

30-
// Check if all elements are strings
31-
const allStrings = parsed.every((item) => typeof item === "string");
32-
if (!allStrings) {
33-
return res.status(400).send("All array elements must be strings");
34-
}
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+
}
3528

36-
req.body = parsed;
37-
next();
38-
} catch (error) {
39-
console.error("Failed to parse JSON:", error);
40-
res.status(400).send("Invalid JSON");
41-
}
42-
});
29+
next();
4330
}
4431

4532
// Apply middlewares
4633
app.use(extractUsername);
47-
app.post("/", parseJsonArrayBody, (req, res) => {
34+
app.post("/", validateArrayOfStrings, (req, res) => {
4835
const authMessage = req.username
4936
? `You are authenticated as ${req.username}.`
5037
: "You are not authenticated.";

0 commit comments

Comments
 (0)