|
| 1 | +import express from "express"; |
| 2 | +const app = express(); |
| 3 | +app.use(express.text()); |
| 4 | + |
| 5 | +//1st Middleware - Extracting username |
| 6 | + |
| 7 | +function usernameMiddleware(req, res, next){ //middleware always has three parameters. req from client, res you send back and a next function that passes controls to next middleware |
| 8 | + const userName = req.header("X-Username"); //getting a custom HTTP Header from the request |
| 9 | + req.userName = userName || null; //if username is not presnet store null |
| 10 | + next(); // this passes control to the next middleware. |
| 11 | +} |
| 12 | + |
| 13 | +//2nd Middleware - Validating JSON array body |
| 14 | +function jsonArrayMiddleware(req, res, next){ |
| 15 | + let data; |
| 16 | + try { |
| 17 | + data = JSON.parse(req.body); |
| 18 | +} |
| 19 | +catch(err){ |
| 20 | + return res.status(400).send("Body must be valid JSON"); |
| 21 | +} |
| 22 | +if(!Array.isArray(data)){ |
| 23 | + return res.status(400).send("Body must be JSON array"); |
| 24 | + |
| 25 | +} |
| 26 | +if (!data.every(item => typeof item === "string")) { //every item in the array is a string = NOT TRUE |
| 27 | + return res.status(400).send("Array must contain only strings"); |
| 28 | +} |
| 29 | +req.body = data; //store validated array |
| 30 | +next() //allows req to continue to next middleware |
| 31 | +} |
| 32 | + |
| 33 | +// POST route using both middlewares |
| 34 | +app.post("/subjects",usernameMiddleware, jsonArrayMiddleware, (req, res) => { |
| 35 | + const userName = req.userName; |
| 36 | + const subjects = req.body; |
| 37 | + const count = subjects.length; |
| 38 | + const authMessage = userName ? `You are authenticated as ${userName}.` : `You are not authenticated.`; |
| 39 | +// Subject message |
| 40 | + let subjectMessage; |
| 41 | + if (count === 0) { |
| 42 | + subjectMessage = "You have requested information about 0 subjects."; |
| 43 | + } else if (count === 1) { |
| 44 | + subjectMessage = `You have requested information about 1 subject: ${subjects[0]}.`; |
| 45 | + } else { |
| 46 | + subjectMessage = `You have requested information about ${count} subjects: ${subjects.join(", ")}.`; |
| 47 | + } |
| 48 | + |
| 49 | + // Send final response |
| 50 | + res.send(`${authMessage}\n\n${subjectMessage}`); |
| 51 | +}); |
| 52 | + |
| 53 | +const PORT = 3000 |
| 54 | +app.listen(PORT, () => { |
| 55 | + console.log(`Server running on http://localhost:${PORT}`) |
| 56 | +}); |
0 commit comments