|
| 1 | +import express from "express"; |
| 2 | + |
| 3 | +const app = express(); |
| 4 | + |
| 5 | +// Built-in Express middleware to parse JSON automatically |
| 6 | +app.use(express.json()); |
| 7 | + |
| 8 | +// Custom middleware: Get username from header |
| 9 | +function usernameExtractor(req, res, next) { |
| 10 | + const username = req.get("X-Username"); |
| 11 | + req.username = username ? username : null; |
| 12 | + next(); |
| 13 | +} |
| 14 | + |
| 15 | +app.use(usernameExtractor); |
| 16 | + |
| 17 | +app.post("/", (req, res) => { |
| 18 | + const username = req.username; // from header |
| 19 | + const subjects = req.body; // parsed JSON from express.json() |
| 20 | + |
| 21 | + if (!Array.isArray(subjects)) { |
| 22 | + return res.status(400).send("Error: Body must be a JSON array."); |
| 23 | + } |
| 24 | + |
| 25 | + const allStrings = subjects.every((item) => typeof item === "string"); |
| 26 | + if (!allStrings) { |
| 27 | + return res |
| 28 | + .status(400) |
| 29 | + .send("Error: Array must contain only string elements."); |
| 30 | + } |
| 31 | + |
| 32 | + const authMessage = username |
| 33 | + ? `You are authenticated as ${username}.` |
| 34 | + : "You are not authenticated."; |
| 35 | + |
| 36 | + const subjectCount = subjects.length; |
| 37 | + const subjectList = subjects.join(", "); |
| 38 | + |
| 39 | + const infoMessage = |
| 40 | + subjectCount === 0 |
| 41 | + ? "You have requested information about 0 subjects." |
| 42 | + : `You have requested information about ${subjectCount} subject${ |
| 43 | + subjectCount > 1 ? "s" : "" |
| 44 | + }: ${subjectList}.`; |
| 45 | + |
| 46 | + res.send(`${authMessage}\n\n${infoMessage}`); |
| 47 | +}); |
| 48 | + |
| 49 | +// Start the server |
| 50 | +const PORT = 3001; |
| 51 | +app.listen(PORT, () => { |
| 52 | + console.log(`Server running on http://localhost:${PORT}`); |
| 53 | +}); |
0 commit comments