Skip to content

Commit f923654

Browse files
Refactor: replace custom body parser with express.json built-in middleware
1 parent 365d2f4 commit f923654

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

app-builtin.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
const express = require('express');
2+
const app = express();
3+
app.use(express.json());
4+
5+
// Header Middleware
6+
const checkUsername = (req, res, next) => {
7+
const usernameHeader = req.get("X-Username");
8+
req.username = usernameHeader || null;
9+
next();
10+
};
11+
12+
13+
// validates data
14+
const validateSubjects = (req, res, next) => {
15+
16+
const subjects = req.body;
17+
18+
if (
19+
!Array.isArray(subjects) ||
20+
!subjects.every((item) => typeof item === "string")
21+
) {
22+
return res.status(400).send("Invalid input: expected an array of strings.");
23+
}
24+
next();
25+
};
26+
27+
28+
29+
// The Endpoint
30+
app.post("/subjects", checkUsername, validateSubjects, (req, res) => {
31+
const { username, body: subjects } = req;
32+
33+
// Handle Authentication Message
34+
const authPart = username
35+
? `You are authenticated as ${username}.`
36+
: "You are not authenticated.";
37+
38+
// Handle subject vs subjects
39+
const count = subjects.length;
40+
const subjectText = count === 1 ? "subject" : "subjects";
41+
42+
// 3. Handle the list formatting
43+
const listPart = count > 0 ? `: ${subjects.join(", ")}.` : ".";
44+
45+
res.send(
46+
`${authPart}\n\nYou have requested information about ${count} ${subjectText}${listPart}`,
47+
);
48+
});
49+
50+
51+
52+
app.listen(3000, () => {
53+
console.log('Server is running on port 3000');
54+
});

0 commit comments

Comments
 (0)