|
| 1 | +import express from "express"; |
| 2 | + |
| 3 | +const app = express(); |
| 4 | +const PORT = 3000; |
| 5 | + |
| 6 | +// Middleware 1: Extract username from X-Username header |
| 7 | +function extractUsername(req, res, next) { |
| 8 | + const username = req.headers["x-username"]; |
| 9 | + req.username = username || null; |
| 10 | + next(); |
| 11 | +} |
| 12 | + |
| 13 | +// Use built-in Express JSON middleware instead of custom one |
| 14 | +app.use(extractUsername); |
| 15 | +app.use(express.json()); |
| 16 | + |
| 17 | +app.post("/", (req, res) => { |
| 18 | + // Validate that body is an array |
| 19 | + if (!Array.isArray(req.body)) { |
| 20 | + return res.status(400).send("Request body must be a JSON array"); |
| 21 | + } |
| 22 | + |
| 23 | + // Check if all elements are strings |
| 24 | + const allStrings = req.body.every((item) => typeof item === "string"); |
| 25 | + if (!allStrings) { |
| 26 | + return res.status(400).send("All array elements must be strings"); |
| 27 | + } |
| 28 | + |
| 29 | + const authMessage = req.username |
| 30 | + ? `You are authenticated as ${req.username}.` |
| 31 | + : "You are not authenticated."; |
| 32 | + |
| 33 | + const count = req.body.length; |
| 34 | + let subjectsMessage; |
| 35 | + if (count === 0) { |
| 36 | + subjectsMessage = "You have requested information about 0 subjects."; |
| 37 | + } else if (count === 1) { |
| 38 | + subjectsMessage = `You have requested information about 1 subject: ${req.body[0]}.`; |
| 39 | + } else { |
| 40 | + subjectsMessage = `You have requested information about ${count} subjects: ${req.body.join( |
| 41 | + ", " |
| 42 | + )}.`; |
| 43 | + } |
| 44 | + |
| 45 | + res.send(`${authMessage}\n\n${subjectsMessage}\n`); |
| 46 | +}); |
| 47 | + |
| 48 | +app.listen(PORT, () => { |
| 49 | + console.log(`Server running on http://localhost:${PORT}`); |
| 50 | +}); |
0 commit comments