generated from CodeYourFuture/Module-Template
-
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathapp.js
More file actions
68 lines (50 loc) · 1.54 KB
/
app.js
File metadata and controls
68 lines (50 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const express = require('express');
const app = express();
// 1. Header Middleware
const checkUsername = (req, res, next) => {
const usernameHeader = req.get("X-Username");
req.username = usernameHeader || null;
next();
};
// 2. Body Parser Middleware
const ensureJsonStringArray = (req, res, next) => {
let rawBody = "";
req.on("data", (chunk) => {
rawBody += chunk;
});
req.on("end", () => {
let parsed;
try {
parsed = JSON.parse(rawBody);
} catch {
return res.status(400).send("Request body must be valid JSON");
}
if (!Array.isArray(parsed)) {
return res.status(400).send("Request body must be a JSON array");
}
if (!parsed.every((item) => typeof item === "string")) {
return res.status(400).send("Array must contain only strings");
}
req.body = parsed;
next();
});
};
// 3. The Endpoint
app.post("/subjects", checkUsername, ensureJsonStringArray, (req, res) => {
const { username, body: subjects } = req;
// Handle Authentication Message
const authPart = username
? `You are authenticated as ${username}.`
: "You are not authenticated.";
// Handle subject vs subjects
const count = subjects.length;
const subjectText = count === 1 ? "subject" : "subjects";
// 3. Handle the list formatting
const listPart = count > 0 ? `: ${subjects.join(", ")}.` : ".";
res.send(
`${authPart}\n\nYou have requested information about ${count} ${subjectText}${listPart}`,
);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});