11import express from 'express' ;
2+
23const app = express ( ) ;
4+ const PORT = 3000 ;
35
4- // Built-in middleware to parse JSON bodies
6+ // Parse JSON bodies(built-in)
57app . use ( express . json ( ) ) ;
68
7- // Middleware 1: Extract username from header or set to null
9+ // Middleware1, Extract username from header
810function usernameMiddleware ( req , res , next ) {
911 const username = req . header ( 'X-Username' ) ;
1012 req . username = username || null ;
1113 next ( ) ;
1214}
1315
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- }
2216
23- const authMessage = req . username
24- ? 'You are authenticated as ' + req . username + '.'
25- : 'You are not authenticated.' ;
17+ //Reusable validator
18+ function validateArrayOf ( type ) {
19+ return function ( req , res , next ) {
20+ if (
21+ ! Array . isArray ( req . body ) ||
22+ ! req . body . every ( item => typeof item === type )
23+ ) {
24+ return res
25+ . status ( 400 )
26+ . send ( `Invalid body: must be JSON array of ${ type } s` ) ;
27+ }
2628
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.' ;
29+ next ( ) ;
30+ } ;
31+ }
3332
34- res . send ( authMessage + '\n\n' + subjectMessage ) ;
35- } ) ;
33+ // Route
3634
37- const PORT = 3000 ;
38- app . listen ( PORT , function ( ) {
39- console . log ( 'Server running on http://localhost:' + PORT ) ;
40- } ) ;
35+ app . post (
36+ '/info' ,
37+ usernameMiddleware ,
38+ validateArrayOf ( 'string' ) ,
39+ ( req , res ) => {
40+ const authMessage = req . username
41+ ? `You are authenticated as ${ req . username } .`
42+ : 'You are not authenticated.' ;
43+
44+ const count = req . body . length ;
45+ const subjects = req . body . join ( ', ' ) ;
46+ const subjectWord = count === 1 ? 'subject' : 'subjects' ;
47+
48+ const subjectMessage = count
49+ ? `You have requested information about ${ count } ${ subjectWord } : ${ subjects } .`
50+ : 'You have requested information about 0 subjects.' ;
51+
52+ res . send ( `${ authMessage } \n\n${ subjectMessage } ` ) ;
53+ }
54+ ) ;
55+
56+ app . listen ( PORT , ( ) => {
57+ console . log ( `Server running on http://localhost:${ PORT } ` ) ;
58+ } ) ;
0 commit comments