Skip to content

Commit 557fe4e

Browse files
committed
refactor: split JSON parsing and string validation into separate middlewares
1 parent de23b11 commit 557fe4e

2 files changed

Lines changed: 22 additions & 17 deletions

File tree

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
{
22
"name": "module-decomposition",
33
"version": "1.0.0",
4+
"type": "module",
45
"description": "Exercises to practice and solidify your understanding of the Decomposition module of the Software Development Course.",
56
"main": "index.js",
67
"scripts": {

two-custom-written-middlewares/express.js

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ function usernameExtractor(req, res, next) {
1111
next();
1212
}
1313

14-
// Parses body as JSON array and validates string elements
15-
function jsonArrayValidator(req, res, next) {
14+
// Parses raw request body as JSON
15+
function jsonBodyParser(req, res, next) {
1616
let data = "";
1717

1818
req.on("data", (chunk) => {
@@ -22,31 +22,35 @@ function jsonArrayValidator(req, res, next) {
2222
req.on("end", () => {
2323
try {
2424
const parsed = JSON.parse(data); // try to parse JSON
25-
26-
if (!Array.isArray(parsed)) {
27-
return res.status(400).send("Error: Body must be a JSON array.");
28-
}
29-
30-
const allStrings = parsed.every((item) => typeof item === "string");
31-
if (!allStrings) {
32-
return res
33-
.status(400)
34-
.send("Error: Array must contain only string elements.");
35-
}
36-
37-
req.body = parsed; // save valid array
38-
next();
25+
req.body = parsed; // attach parsed object to req
26+
next();
3927
} catch (err) {
4028
res.status(400).send("Error: Invalid JSON.");
4129
}
4230
});
4331
}
4432

33+
// Validates that req.body is a string array
34+
function stringArrayValidator(req, res, next) {
35+
if (!Array.isArray(req.body)) {
36+
return res.status(400).send("Error: Body must be a JSON array.");
37+
}
38+
39+
const allStrings = req.body.every((item) => typeof item === "string");
40+
if (!allStrings) {
41+
return res
42+
.status(400)
43+
.send("Error: Array must contain only string elements.");
44+
}
45+
46+
next();
47+
}
48+
4549
// Applies the first middleware to all routes
4650
app.use(usernameExtractor);
4751

4852
// Handles POST requests and builds response message
49-
app.post("/", jsonArrayValidator, (req, res) => {
53+
app.post("/", jsonBodyParser, stringArrayValidator, (req, res) => {
5054
const username = req.username;
5155
const subjects = req.body;
5256

0 commit comments

Comments
 (0)