Skip to content

Commit c666569

Browse files
committed
refactoring with existing middleware.
1 parent c298307 commit c666569

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

Off-the-shelf middleware/script.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import express from 'express';
2+
const app = express();
3+
4+
// Built-in middleware to parse JSON bodies
5+
app.use(express.json());
6+
7+
// Middleware 1: Extract username from header or set to null
8+
function usernameMiddleware(req, res, next) {
9+
const username = req.header('X-Username');
10+
req.username = username || null;
11+
next();
12+
}
13+
14+
app.post('/info', usernameMiddleware, function(req, res) {
15+
// req.body is now automatically parsed by express.json()
16+
if (
17+
!Array.isArray(req.body) ||
18+
!req.body.every(function(item) { return typeof item === 'string'; })
19+
) {
20+
return res.status(400).send('Invalid body: must be JSON array of strings');
21+
}
22+
23+
const authMessage = req.username
24+
? 'You are authenticated as ' + req.username + '.'
25+
: 'You are not authenticated.';
26+
27+
const count = req.body.length;
28+
const subjects = req.body.join(', ');
29+
const subjectWord = count === 1 ? 'subject' : 'subjects';
30+
const subjectMessage = count
31+
? 'You have requested information about ' + count + ' ' + subjectWord + ': ' + subjects + '.'
32+
: 'You have requested information about 0 subjects.';
33+
34+
res.send(authMessage + '\n\n' + subjectMessage);
35+
});
36+
37+
const PORT = 3000;
38+
app.listen(PORT, function() {
39+
console.log('Server running on http://localhost:' + PORT);
40+
});

0 commit comments

Comments
 (0)