Skip to content

Commit 25b3feb

Browse files
app and middlewares
1 parent db9653b commit 25b3feb

3 files changed

Lines changed: 59 additions & 1 deletion

File tree

middleware-costum/app.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,31 @@
11
import express from "express";
2+
import usernameMiddleware from "./middleware/usernameMiddleware";
3+
import jsonArrayMiddleware from "./middleware/jsonArrayMiddleware";
24

35
const app = express();
46

7+
app.post("/", usernameMiddleware, jsonArrayMiddleware, (req, res) => {
8+
const subjects = req.body;
9+
10+
const auth =
11+
req.username
12+
? `You are authenticated as ${req.username}.`
13+
: "You are not authenticated.";
14+
15+
let message = "";
16+
17+
if (subjects.length === 0) {
18+
message = "You have requested information about 0 subjects.";
19+
} else if (subjects.length === 1) {
20+
message = `You have requested information about 1 subject: ${subjects[0]}.`;
21+
} else {
22+
message = `You have requested information about ${subjects.length} subjects: ${subjects.join(", ")}.`;
23+
}
24+
25+
res.send(`${auth}\n\n${message}`);
26+
});
27+
28+
29+
app.listen(3000, () => {
30+
console.log("Server running on 3000");
31+
});
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
export default function jsonArrayMiddleware(req, res, next) {
2+
const chunks = [];
3+
4+
req.on("data", (chunk) => {
5+
chunks.push(chunk);
6+
});
7+
8+
req.on("end", () => {
9+
const bodyString = Buffer.concat(chunks).toString();
10+
11+
let data;
12+
13+
try {
14+
data = JSON.parse(bodyString);
15+
} catch {
16+
return res.status(400).send("Invalid JSON");
17+
}
18+
19+
if (!Array.isArray(data)) {
20+
return res.status(400).send("Body must be an array");
21+
}
22+
23+
if (!data.every(item => typeof item === "string")) {
24+
return res.status(400).send("Array must contain only strings");
25+
}
26+
27+
req.body = data;
28+
29+
next();
30+
});
31+
}

middleware-costum/middleware/usernameMiddleware.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
function usernameMiddleware(req, res, next) {
1+
export default function usernameMiddleware(req, res, next) {
22
const username = req.header("X-Username");
33

44
req.username = username || null;

0 commit comments

Comments
 (0)