Skip to content

Commit 0a9b4cb

Browse files
committed
Refactor jsonArrayMiddleware into reusable middlewares for parsing and validation
1 parent f6b7737 commit 0a9b4cb

1 file changed

Lines changed: 61 additions & 62 deletions

File tree

middleware_exercise/custom_middleware/expressmiddlewareapp.js

Lines changed: 61 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -2,77 +2,76 @@
22
const express = require("express");
33
const app = express();
44
//my first middleware , request/get the header and attach it to req
5-
65
function userNameMiddleware(req, res, next) {
7-
const username = req.header("X-Username");
8-
req.username = username ? username : null;
9-
next(); //to pass control onward
6+
const username = req.header("X-Username");
7+
req.username = username ? username : null;
8+
next(); //to pass control onward
109
}
11-
12-
//my second middleware json array middleware.. manually parsing raw body into json
13-
function jsonArrayMiddleware(req, res, next) {
14-
let data = '';
15-
16-
//collecting the chunk of data as soon as they arrive
17-
req.on("data", chunk => {
18-
data += chunk;
19-
});
20-
21-
req.on("end", () => {
22-
try {
23-
const parsed = JSON.parse(data);
24-
25-
//checking if it is an array
26-
if (!Array.isArray(parsed)) {
27-
return res.status(400).send("Request body must be a JSON array.");
28-
}
29-
// check every item is a string
30-
const allStrings = parsed.every((item) => typeof item === "string");
31-
if (!allStrings) {
32-
return res.status(400).send("All array elements must be strings.");
33-
}
34-
35-
req.body = parsed;
36-
next();
37-
} catch (err) {
38-
res.status(400).send("Invalid JSON.");
39-
}
40-
});
10+
// middleware 1: parse raw JSON into req.body
11+
function parseJsonMiddleware(req, res, next) {
12+
let data = '';
13+
// collecting the chunk of data as soon as they arrive
14+
req.on("data", chunk => {
15+
data += chunk;
16+
});
17+
req.on("end", () => {
18+
try {
19+
req.body = JSON.parse(data); // parse JSON only, no checks yet
20+
next();
21+
} catch (err) {
22+
res.status(400).send("Invalid JSON.");
23+
}
24+
});
4125
}
26+
// middleware 2 check if req.body is an array
27+
function validateArrayMiddleware(req, res, next) {
28+
if (!Array.isArray(req.body)) {
29+
return res.status(400).send("Request body must be a JSON array.");
30+
}
31+
next();
32+
}
33+
// middleware 3: check if every item in the array is a string
34+
function validateStringArrayMiddleware(req, res, next) {
35+
const allStrings = req.body.every((item) => typeof item === "string");
36+
if (!allStrings) {
37+
return res.status(400).send("All array elements must be strings.");
38+
}
39+
next();
40+
}
41+
// my route handler
42+
app.post(
43+
"/",
44+
userNameMiddleware,
45+
parseJsonMiddleware,
46+
validateArrayMiddleware,
47+
validateStringArrayMiddleware,
48+
(req, res) => {
49+
const username = req.username;
50+
const subjects = req.body;
51+
const count = subjects.length;
4252

43-
//my route handler
44-
app.post("/", userNameMiddleware, jsonArrayMiddleware, (req, res) => {
45-
const username = req.username;
46-
const subjects = req.body;
47-
const count = subjects.length;
48-
49-
let response = "";
53+
let response = "";
5054

51-
// Auth message
52-
if (username) {
53-
response += `You are authenticated as ${username}.\n\n`;
54-
} else {
55-
response += "You are not authenticated.\n\n";
56-
}
55+
if (username) {
56+
response += `You are authenticated as ${username}.\n\n`;
57+
} else {
58+
response += "You are not authenticated.\n\n";
59+
}
60+
if (count === 1) {
61+
response += `You have requested information about 1 subject: ${subjects[0]}.`;
62+
} else if (count > 1) {
63+
response += `You have requested information about ${count} subjects: ${subjects.join(", ")}.`;
64+
} else {
65+
response += "You have requested information about 0 subjects.";
66+
}
5767

58-
// Subject count message
59-
if (count === 1) {
60-
response += `You have requested information about 1 subject: ${subjects[0]}.`;
61-
} else if (count > 1) {
62-
response += `You have requested information about ${count} subjects: ${subjects.join(
63-
", "
64-
)}.`;
65-
} else {
66-
response += "You have requested information about 0 subjects.";
68+
res.send(response);
6769
}
70+
);
6871

69-
res.send(response);
70-
});
71-
72-
//start the server
7372
app.listen(3000, () => {
7473
console.log("Server running on http://localhost:3000");
7574
});
7675

77-
//to run node app.js
78-
//on other terminal curl -X POST --data '["Bees"]' -H "X-Username: Ahmed" http://localhost:3000
76+
// to run: node app.js
77+
// on another terminal: curl -X POST --data '["Bees"]' -H "X-Username: Ahmed" http://localhost:3000

0 commit comments

Comments
 (0)