Skip to content

Commit db43eab

Browse files
committed
refactor: extract body validation into middleware
1 parent f355149 commit db43eab

1 file changed

Lines changed: 12 additions & 8 deletions

File tree

‎off-shelf-middlewares/off-shelf-middlewares.mjs‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,23 @@ const checkUsername = (req, res, next) => {
44
req.username = req.get("X-Username") ?? null;
55
next();
66
};
7-
app.use(checkUsername);
8-
app.use(express.json());
9-
10-
app.post("/", (req, res) => {
7+
const validateBody = (req,res,next)=>{
118
if (!Array.isArray(req.body)) {
12-
res.status(400).send("Expected body to be an array.");
13-
return;
9+
return res.status(400).send("Expected body to be an array.");
1410
}
1511
const allString = req.body.every((item) => typeof item === "string");
1612
if (!allString) {
17-
res.status(400).send("Expected all array elements to be strings.");
18-
return;
13+
return res.status(400).send("Expected all array elements to be strings.");
14+
1915
}
16+
next();
17+
}
18+
app.use(checkUsername);
19+
app.use(express.json());
20+
app.use(validateBody);
21+
22+
app.post("/", (req, res) => {
23+
2024
let response = "";
2125
if (req.username) {
2226
response += `You are authenticated as ${req.username}.`;

0 commit comments

Comments
 (0)