1+ const express = require ( 'express' ) ;
2+ const app = express ( ) ;
3+ app . use ( express . json ( ) ) ;
4+
5+ // Header Middleware
6+ const checkUsername = ( req , res , next ) => {
7+ const usernameHeader = req . get ( "X-Username" ) ;
8+ req . username = usernameHeader || null ;
9+ next ( ) ;
10+ } ;
11+
12+
13+ // validates data
14+ const validateSubjects = ( req , res , next ) => {
15+
16+ const subjects = req . body ;
17+
18+ if (
19+ ! Array . isArray ( subjects ) ||
20+ ! subjects . every ( ( item ) => typeof item === "string" )
21+ ) {
22+ return res . status ( 400 ) . send ( "Invalid input: expected an array of strings." ) ;
23+ }
24+ next ( ) ;
25+ } ;
26+
27+
28+
29+ // The Endpoint
30+ app . post ( "/subjects" , checkUsername , validateSubjects , ( req , res ) => {
31+ const { username, body : subjects } = req ;
32+
33+ // Handle Authentication Message
34+ const authPart = username
35+ ? `You are authenticated as ${ username } .`
36+ : "You are not authenticated." ;
37+
38+ // Handle subject vs subjects
39+ const count = subjects . length ;
40+ const subjectText = count === 1 ? "subject" : "subjects" ;
41+
42+ // 3. Handle the list formatting
43+ const listPart = count > 0 ? `: ${ subjects . join ( ", " ) } .` : "." ;
44+
45+ res . send (
46+ `${ authPart } \n\nYou have requested information about ${ count } ${ subjectText } ${ listPart } ` ,
47+ ) ;
48+ } ) ;
49+
50+
51+
52+ app . listen ( 3000 , ( ) => {
53+ console . log ( 'Server is running on port 3000' ) ;
54+ } ) ;
0 commit comments