Skip to content

Commit 0cfc2d1

Browse files
committed
Add middleware: X-username header and JSON string-array body parser
- Add username middleware that reads X-username header and sets req.username (or null). - Add array middleware that accumulates request bytes, parses JSON, validates it's an array of strings, assigns req.body or returns 400 on invalid input. - Add package.json with Express dependency.
1 parent edd1159 commit 0cfc2d1

2 files changed

Lines changed: 58 additions & 0 deletions

File tree

middleware-exercise/app.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import express from "express";
2+
3+
const usernameMiddleware = (req, res, next) => {
4+
const headerValue = req.get("X-username");
5+
6+
if (headerValue) {
7+
req.username = headerValue;
8+
} else {
9+
req.username = null;
10+
}
11+
12+
next();
13+
};
14+
15+
const arrayMiddleware = (req, res, next) => {
16+
const bodyBytes = [];
17+
18+
// Every time a piece of data arrives, we put it in our list
19+
req.on("data", (chunk) => {
20+
bodyBytes.push(...chunk);
21+
});
22+
23+
// When the whole message has arrived, we process it
24+
req.on("end", () => {
25+
const bodyString = String.fromCharCode(...bodyBytes);
26+
27+
const bodyObject = JSON.parse(bodyString);
28+
29+
if (
30+
Array.isArray(bodyObject) &&
31+
bodyObject.every((item) => typeof item === "string")
32+
) {
33+
req.body = bodyObject;
34+
next();
35+
} else {
36+
res
37+
.status(400)
38+
.send(
39+
"Invalid request body. Expected a JSON array containing only strings.",
40+
);
41+
}
42+
});
43+
};

middleware-exercise/package.json

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"name": "middleware-exercise",
3+
"version": "1.0.0",
4+
"description": "",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"keywords": [],
10+
"author": "",
11+
"license": "ISC",
12+
"dependencies": {
13+
"express": "^5.2.1"
14+
}
15+
}

0 commit comments

Comments
 (0)