Skip to content

Commit cdcd596

Browse files
committed
Add Express app with username and array-validation middleware
- Add off-the-shelf-middleware.js: create Express app and listen on PORT (env fallback to 3000). - Add username middleware (reads X-username header into req.username). - Add validateArray middleware (ensures JSON body is an array of strings; returns 400 on invalid input). - Add POST "/" route that composes a response using the middlewares and starts the server.
1 parent 8402a16 commit cdcd596

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import express from "express";
2+
3+
const app = express();
4+
5+
const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
6+
7+
const usernameMiddleware = (req, res, next) => {
8+
const headerValue = req.get("X-username");
9+
10+
if (headerValue) {
11+
req.username = headerValue;
12+
} else {
13+
req.username = null;
14+
}
15+
16+
next();
17+
};
18+
19+
app.use(express.json());
20+
21+
const validateArray = (req, res, next) => {
22+
if (
23+
req.body &&
24+
Array.isArray(req.body) &&
25+
req.body.every((item) => typeof item === "string")
26+
) {
27+
next();
28+
} else {
29+
res.status(400).send("Error message");
30+
}
31+
};
32+
33+
// Hey Express, whenever a POST request arrives at '/', please call this person first (usernameMiddleware), then this person (arrayMiddleware), then finally do the route logic.
34+
app.post("/", usernameMiddleware, validateArray, (req, res) => {
35+
let authPart;
36+
if (req.username) {
37+
authPart = `You are authenticated as ${req.username}`;
38+
} else {
39+
authPart = "You are not authenticated";
40+
}
41+
const MessageCount = req.body.length;
42+
43+
const messageJoined = req.body.join(",");
44+
45+
const word = MessageCount === 1 ? "subject" : "subjects";
46+
47+
if (MessageCount > 0) {
48+
res.send(
49+
`${authPart}\n\nYou have requested information about ${MessageCount} ${word}: ${messageJoined}.`,
50+
);
51+
} else {
52+
res.send(
53+
`${authPart}\n\nYou have requested information about ${MessageCount} ${word}.`,
54+
);
55+
}
56+
});
57+
58+
app.listen(PORT, () => {
59+
console.log("Type your message here");
60+
});

0 commit comments

Comments
 (0)