|
| 1 | +import express from "express"; |
| 2 | +import usernameMiddleware from "./middleware/usernameMiddleware.js"; |
| 3 | + |
| 4 | +const app = express(); |
| 5 | +app.use(express.json()); |
| 6 | + |
| 7 | +function jsonArrayValidator(req, res, next) { |
| 8 | + const body = req.body; |
| 9 | + |
| 10 | + if (!Array.isArray(body)) { |
| 11 | + return res.status(400).send("Bad Request: Expected a JSON array."); |
| 12 | + } |
| 13 | + |
| 14 | + const allStrings = body.every((item) => typeof item === "string"); |
| 15 | + if (!allStrings) { |
| 16 | + return res |
| 17 | + .status(400) |
| 18 | + .send("Bad Request: All items in the array must be strings."); |
| 19 | + } |
| 20 | + req.subjects = body; |
| 21 | + next(); |
| 22 | +} |
| 23 | + |
| 24 | +app.post("/", usernameMiddleware, jsonArrayValidator, (req, res) => { |
| 25 | + const username = req.username; |
| 26 | + const subjects = req.subjects; |
| 27 | + |
| 28 | + const authMessage = username |
| 29 | + ? `You are authenticated as ${username}!` |
| 30 | + : "You are not authenticated."; |
| 31 | + |
| 32 | + const count = subjects.length; |
| 33 | + const list = subjects.join(", "); |
| 34 | + |
| 35 | + let subjectMessage; |
| 36 | + if (count === 0) { |
| 37 | + subjectMessage = "You have no subjects."; |
| 38 | + } else if (count === 1) { |
| 39 | + subjectMessage = `You have 1 subject: ${list}.`; |
| 40 | + } else { |
| 41 | + subjectMessage = `You have ${count} subjects: ${list}.`; |
| 42 | + } |
| 43 | + res.send(`${authMessage} ${subjectMessage}`); |
| 44 | +}); |
| 45 | + |
| 46 | +app.listen(3000, () => { |
| 47 | + console.log("Off-the-shelf server is running on port 3000"); |
| 48 | +}); |
0 commit comments