Skip to content

Commit 56aadb0

Browse files
Refactor middleware functions for clarity and reuse
1 parent 4579661 commit 56aadb0

1 file changed

Lines changed: 43 additions & 28 deletions

File tree

Middleware-custom/app.js

Lines changed: 43 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,54 +3,69 @@ const app = express();
33
const PORT = 3000;
44

55
// Middleware 1: Check username header
6-
app.use((req, res, next) => {
6+
function checkUsername(req, res, next) {
77
req.username = req.headers['x-username'] || null;
88
next();
9-
});
9+
}
1010

11-
// Middleware 2: Parse JSON and check if body is string array
12-
app.use((req, res, next) => {
11+
// Middleware 2: Parse JSON
12+
function parseJson(req, res, next) {
1313
if (req.method !== 'POST') return next();
14-
14+
1515
let body = '';
16+
1617
req.on('data', chunk => {
1718
body += chunk.toString();
1819
});
19-
20+
2021
req.on('end', () => {
2122
try {
2223
req.body = JSON.parse(body);
24+
next();
2325
} catch (error) {
24-
return res.status(400).send('Error: Invalid JSON');
25-
}
26-
27-
// Simple array check
28-
if (!Array.isArray(req.body)) {
29-
return res.status(400).send('Error: Send a JSON array');
26+
res.status(400).send('Error: Invalid JSON');
3027
}
31-
32-
// Simple string check
33-
for (let item of req.body) {
34-
if (typeof item !== 'string') {
35-
return res.status(400).send('Error: All items must be strings');
36-
}
37-
}
38-
39-
req.subjects = req.body;
40-
next();
4128
});
42-
});
29+
}
30+
31+
// Middleware 3: Validate array of strings
32+
function validateStringArray(req, res, next) {
33+
if (req.method !== 'POST') return next();
34+
35+
if (!Array.isArray(req.body)) {
36+
return res.status(400).send('Error: Send a JSON array');
37+
}
38+
39+
for (const item of req.body) {
40+
if (typeof item !== 'string') {
41+
return res.status(400).send('Error: All items must be strings');
42+
}
43+
}
44+
45+
req.subjects = req.body;
46+
next();
47+
}
48+
49+
// Register middleware
50+
app.use(checkUsername);
51+
app.use(parseJson);
52+
app.use(validateStringArray);
4353

4454
// POST endpoint
4555
app.post('/', (req, res) => {
46-
const name = req.username ? `authenticated as ${req.username}` : 'not authenticated';
56+
const name = req.username
57+
? `authenticated as ${req.username}`
58+
: 'not authenticated';
59+
4760
const count = req.subjects.length;
4861
const word = count === 1 ? 'subject' : 'subjects';
4962
const list = req.subjects.join(', ');
50-
51-
res.send(`You are ${name}.\n\nYou asked about ${count} ${word}: ${list}.`);
63+
64+
res.send(
65+
`You are ${name}.\n\nYou asked about ${count} ${word}: ${list}.`
66+
);
5267
});
5368

5469
app.listen(PORT, () => {
55-
console.log('Custom server started on port 3000');
56-
});
70+
console.log(`Custom server started on port ${PORT}`);
71+
});

0 commit comments

Comments
 (0)