@@ -11,8 +11,8 @@ function usernameExtractor(req, res, next) {
1111 next ( ) ;
1212}
1313
14- // Parses body as JSON array and validates string elements
15- function jsonArrayValidator ( req , res , next ) {
14+ // Parses raw request body as JSON
15+ function jsonBodyParser ( req , res , next ) {
1616 let data = "" ;
1717
1818 req . on ( "data" , ( chunk ) => {
@@ -22,31 +22,35 @@ function jsonArrayValidator(req, res, next) {
2222 req . on ( "end" , ( ) => {
2323 try {
2424 const parsed = JSON . parse ( data ) ; // try to parse JSON
25-
26- if ( ! Array . isArray ( parsed ) ) {
27- return res . status ( 400 ) . send ( "Error: Body must be a JSON array." ) ;
28- }
29-
30- const allStrings = parsed . every ( ( item ) => typeof item === "string" ) ;
31- if ( ! allStrings ) {
32- return res
33- . status ( 400 )
34- . send ( "Error: Array must contain only string elements." ) ;
35- }
36-
37- req . body = parsed ; // save valid array
38- next ( ) ;
25+ req . body = parsed ; // attach parsed object to req
26+ next ( ) ;
3927 } catch ( err ) {
4028 res . status ( 400 ) . send ( "Error: Invalid JSON." ) ;
4129 }
4230 } ) ;
4331}
4432
33+ // Validates that req.body is a string array
34+ function stringArrayValidator ( req , res , next ) {
35+ if ( ! Array . isArray ( req . body ) ) {
36+ return res . status ( 400 ) . send ( "Error: Body must be a JSON array." ) ;
37+ }
38+
39+ const allStrings = req . body . every ( ( item ) => typeof item === "string" ) ;
40+ if ( ! allStrings ) {
41+ return res
42+ . status ( 400 )
43+ . send ( "Error: Array must contain only string elements." ) ;
44+ }
45+
46+ next ( ) ;
47+ }
48+
4549// Applies the first middleware to all routes
4650app . use ( usernameExtractor ) ;
4751
4852// Handles POST requests and builds response message
49- app . post ( "/" , jsonArrayValidator , ( req , res ) => {
53+ app . post ( "/" , jsonBodyParser , stringArrayValidator , ( req , res ) => {
5054 const username = req . username ;
5155 const subjects = req . body ;
5256
0 commit comments