Skip to content

Commit f92bf3a

Browse files
committed
Add Sprint 3 task: off-the-shelf middleware version
1 parent 810039b commit f92bf3a

5 files changed

Lines changed: 897 additions & 0 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules

middleware-off-the-shelf/app.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import express from "express";
2+
import usernameMiddleware from "./middleware/usernameMiddleware.js";
3+
4+
const app = express();
5+
app.use(express.json());
6+
7+
function jsonArrayValidator(req, res, next) {
8+
const body = req.body;
9+
10+
if (!Array.isArray(body)) {
11+
return res.status(400).send("Bad Request: Expected a JSON array.");
12+
}
13+
14+
const allStrings = body.every((item) => typeof item === "string");
15+
if (!allStrings) {
16+
return res
17+
.status(400)
18+
.send("Bad Request: All items in the array must be strings.");
19+
}
20+
req.subjects = body;
21+
next();
22+
}
23+
24+
app.post("/", usernameMiddleware, jsonArrayValidator, (req, res) => {
25+
const username = req.username;
26+
const subjects = req.subjects;
27+
28+
const authMessage = username
29+
? `You are authenticated as ${username}!`
30+
: "You are not authenticated.";
31+
32+
const count = subjects.length;
33+
const list = subjects.join(", ");
34+
35+
let subjectMessage;
36+
if (count === 0) {
37+
subjectMessage = "You have no subjects.";
38+
} else if (count === 1) {
39+
subjectMessage = `You have 1 subject: ${list}.`;
40+
} else {
41+
subjectMessage = `You have ${count} subjects: ${list}.`;
42+
}
43+
res.send(`${authMessage} ${subjectMessage}`);
44+
});
45+
46+
app.listen(3000, () => {
47+
console.log("Off-the-shelf server is running on port 3000");
48+
});
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export default function usernameMiddleware(req, res, next) {
2+
const username = req.header("X-Username");
3+
req.username = username ?? null;
4+
next();
5+
}

0 commit comments

Comments
 (0)