1+ import express from "express" ;
2+ const app = express ( ) ;
3+
4+ const usernameMiddleware = ( req , res , next ) => {
5+ req . username = req . get ( "X-Username" ) || null ;
6+ next ( ) ;
7+ } ;
8+
9+ const validateBodyMiddleware = ( req , res , next ) => {
10+ if ( ! Array . isArray ( req . body ) ) {
11+ return res . status ( 400 ) . send ( "Body must be a JSON array" ) ;
12+ }
13+
14+ for ( const item of req . body ) {
15+ if ( typeof item !== "string" ) {
16+ return res
17+ . status ( 400 )
18+ . send ( "All array items must be strings" ) ;
19+ }
20+ }
21+
22+ next ( ) ;
23+ } ;
24+
25+ app . use ( express . json ( ) ) ;
26+ app . use ( usernameMiddleware ) ;
27+ app . use ( validateBodyMiddleware )
28+
29+ app . post ( "/" , ( req , res ) => {
30+ let authenticationMessage ;
31+
32+ if ( req . username ) {
33+ authenticationMessage =
34+ `You are authenticated as ${ req . username } .` ;
35+ } else {
36+ authenticationMessage =
37+ "You are not authenticated." ;
38+ }
39+
40+ const subjects = req . body ;
41+ const numberOfSubjects = subjects . length ;
42+
43+ let subjectsMessage = `You have requested information about ${ numberOfSubjects } subject` ;
44+
45+ if ( numberOfSubjects !== 1 ) {
46+ subjectsMessage += "s" ;
47+ }
48+
49+ if ( numberOfSubjects > 0 ) {
50+ subjectsMessage += `: ${ subjects . join ( ", " ) } ` ;
51+ }
52+
53+ subjectsMessage += "." ;
54+
55+ res . send (
56+ `${ authenticationMessage } \n\n${ subjectsMessage } \n`
57+ ) ;
58+ } ) ;
59+
60+ app . listen ( 3000 , ( ) => {
61+ console . log ( "Server running on port 3000" ) ;
62+ } ) ;
63+
64+
65+ // curl -X POST --data '["Bees"]' -H "Content-Type: application/json" -H "X-Username: Ahmed" http://localhost:3000
0 commit comments