|
| 1 | +const express = require("express"); |
| 2 | +const app = express(); |
| 3 | + |
| 4 | +const PORT = 3000; |
| 5 | + |
| 6 | +app.use(express.json()); |
| 7 | + |
| 8 | +app.listen(PORT, () => { |
| 9 | + console.log(`server running on http://localhost:${PORT} `); |
| 10 | +}); |
| 11 | + |
| 12 | + |
| 13 | +function usernameMiddleware(req, res, next) { |
| 14 | + const username = req.get("X-Username"); |
| 15 | + req.username = username || null; |
| 16 | + next(); |
| 17 | +} |
| 18 | +function bodyMiddleware(req, res, next) { |
| 19 | + const body = req.body; |
| 20 | + if (!Array.isArray(body) || !body.every((el) => typeof el === "string")) { |
| 21 | + return res.status(400).send("Body must be an array of strings"); |
| 22 | + } |
| 23 | + next(); |
| 24 | +} |
| 25 | +app.post("/subjects", usernameMiddleware, bodyMiddleware, (req, res) => { |
| 26 | + const username = req.username; |
| 27 | + const subjects = req.body; |
| 28 | + |
| 29 | + let authMessage; |
| 30 | + |
| 31 | + if (username) { |
| 32 | + authMessage = `You are authenticated as ${username}`; |
| 33 | + } else { |
| 34 | + authMessage = `You are not authenticated.`; |
| 35 | + } |
| 36 | + let countSubject = subjects.length; |
| 37 | + |
| 38 | + let subjectsText; |
| 39 | + if (countSubject === 1) { |
| 40 | + subjectsText = "subject"; |
| 41 | + } else { |
| 42 | + subjectsText = "subjects"; |
| 43 | + } |
| 44 | + |
| 45 | + let subjectList; |
| 46 | + if (countSubject > 0) { |
| 47 | + subjectList = `: ${subjects.join(", ")}`; |
| 48 | + } else { |
| 49 | + subjectList = ""; |
| 50 | + } |
| 51 | + res.send( |
| 52 | + `${authMessage}\n\nYou have requested information about ${countSubject} ${subjectsText}${subjectList}.` |
| 53 | + ); |
| 54 | +}); |
0 commit comments