1+ const express = require ( "express" ) ;
2+
3+ const app = express ( ) ;
4+ const PORT = 3000 ;
5+
6+ // Middleware 1: get username from X-Username header
7+ function usernameMiddleware ( req , res , next ) {
8+ const username = req . get ( "X-Username" ) ;
9+
10+ if ( username ) {
11+ req . username = username ;
12+ } else {
13+ req . username = null ;
14+ }
15+
16+ next ( ) ;
17+ }
18+
19+ // Middleware 2: parse and validate JSON array
20+ function bodyMiddleware ( req , res , next ) {
21+ let body = "" ;
22+
23+ req . on ( "data" , ( chunk ) => {
24+ body += chunk ;
25+ } ) ;
26+
27+ req . on ( "end" , ( ) => {
28+ try {
29+ const parsedBody = JSON . parse ( body ) ;
30+
31+ // Must be an array
32+ if ( ! Array . isArray ( parsedBody ) ) {
33+ return res . status ( 400 ) . send ( "Request body must be a JSON array." ) ;
34+ }
35+
36+ // Every item must be a string
37+ if ( ! parsedBody . every ( ( item ) => typeof item === "string" ) ) {
38+ return res . status ( 400 ) . send ( "Array must contain only strings." ) ;
39+ }
40+
41+ req . body = parsedBody ;
42+ next ( ) ;
43+ } catch ( error ) {
44+ res . status ( 400 ) . send ( "Request body must be valid JSON." ) ;
45+ }
46+ } ) ;
47+ }
48+
49+ // Use our two middlewares
50+ app . use ( usernameMiddleware ) ;
51+ app . use ( bodyMiddleware ) ;
52+
53+ // POST endpoint
54+ app . post ( "/" , ( req , res ) => {
55+ const subjects = req . body ;
56+
57+ if ( req . username ) {
58+ res . send (
59+ `You are authenticated as ${ req . username } .\n\n` +
60+ `You have requested information about ${ subjects . length } ` +
61+ `${ subjects . length === 1 ? "subject" : "subjects" } ` +
62+ `${ subjects . length > 0 ? ": " + subjects . join ( ", " ) : "" } .`
63+ ) ;
64+ } else {
65+ res . send (
66+ `You are not authenticated.\n\n` +
67+ `You have requested information about ${ subjects . length } ` +
68+ `${ subjects . length === 1 ? "subject" : "subjects" } ` +
69+ `${ subjects . length > 0 ? ": " + subjects . join ( ", " ) : "" } .`
70+ ) ;
71+ }
72+ } ) ;
73+
74+ app . listen ( PORT , ( ) => {
75+ console . log ( `Server running on http://localhost:${ PORT } ` ) ;
76+ } ) ;
0 commit comments