@@ -6,35 +6,57 @@ app.use(express.json());
66const userdata = [ ] ;
77const info = [ ] ;
88
9- const usernameValidator = ( req , res , next ) => {
9+ const getUsernameFromHeader = ( req , res , next ) => {
1010 const username = req . headers [ 'x-username' ] ;
1111 userdata . push ( username ) ;
12+ res . locals . username = username ;
13+ next ( ) ;
14+ } ;
1215
13- const userInfo = `You are authenticated as ${ username } ` ;
16+ const checkBodyIsArray = ( req , res , next ) => {
17+ if ( req . body === undefined || req . body === null ) {
18+ res . locals . subjects = [ ] ;
19+ return next ( ) ;
20+ }
1421
15- console . log ( 'req.body =' , req . body ) ;
22+ if ( ! Array . isArray ( req . body ) ) {
23+ return res . status ( 400 ) . send ( 'Request body must be an array of subjects' ) ;
24+ }
25+
26+ res . locals . subjects = req . body ;
27+ next ( ) ;
28+ } ;
29+
30+ const prepareReturnValue = ( req , res , next ) => {
31+ const username = res . locals . username ;
32+ const subjects = res . locals . subjects ?? [ ] ;
1633
17- let userMessage = 'No subjects requested' ;
18- if ( Array . isArray ( req . body ) && req . body . length > 0 ) {
19- info . push ( ...req . body ) ;
20- userMessage = `You have requested information about ${ req . body . length } subjects: ${ req . body . join ( ', ' ) } ` ;
34+ if ( subjects . length > 0 ) {
35+ info . push ( ...subjects ) ;
2136 }
2237
23- console . log ( info ) ;
38+ const userInfo = `You are authenticated as ${ username } ` ;
39+ const userMessage = subjects . length > 0
40+ ? `You have requested information about ${ subjects . length } subjects: ${ subjects . join ( ', ' ) } `
41+ : 'No subjects requested' ;
2442
43+ console . log ( 'req.body =' , req . body ) ;
44+ console . log ( info ) ;
2545 console . log ( `
2646 ${ userInfo }
2747 ${ userMessage }
2848 ` ) ;
2949
50+ res . locals . responseMessage = `Username is ${ username } , Subjects: ${ JSON . stringify ( info ) } ` ;
3051 next ( ) ;
31- }
52+ } ;
3253
33- app . use ( usernameValidator ) ;
54+ app . use ( getUsernameFromHeader ) ;
55+ app . use ( checkBodyIsArray ) ;
56+ app . use ( prepareReturnValue ) ;
3457
3558app . post ( '/' , ( req , res ) => {
36- const username = req . headers [ 'x-username' ] ;
37- res . send ( `Username is ${ username } , Subjects: ${ JSON . stringify ( info ) } ` ) ;
59+ res . send ( res . locals . responseMessage ) ;
3860} ) ;
3961
4062app . listen ( 3000 , ( ) => {
0 commit comments