generated from CodeYourFuture/Module-Template
-
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathparseJsonArrayBody.js
More file actions
34 lines (26 loc) · 692 Bytes
/
parseJsonArrayBody.js
File metadata and controls
34 lines (26 loc) · 692 Bytes
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
function parseJsonArrayBody(req, res, next) {
let data = [];
req.on("data", (chunk) => {
data.push(chunk);
});
req.on("end", () => {
try {
const str = Buffer.concat(data).toString('utf8');
const parsed = JSON.parse(str);
if (!Array.isArray(parsed)) {
return res.status(400).send("Body must be array");
}
const allStrings = parsed.every(
(item) => typeof item === "string"
);
if (!allStrings) {
return res.status(400).send("Must contain strings");
}
req.body = parsed;
next();
} catch {
res.status(400).send("Invalid JSON");
}
});
}
module.exports = parseJsonArrayBody;