-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbarking.js
89 lines (63 loc) · 2.04 KB
/
barking.js
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"use strict";
module.exports = function doBarking (req, res) {
req.setEncoding("utf8");
if (req.body) {
let body = req.body;
let response;
let count = body.count || 1;
let noise = body.noise.toUpperCase();
let sep = body.sep || " ";
if (noise === void 0) {
res.writeHead(400, "Invalid request: 'noise' property required");
}
let msg = [];
for (let _i = 0; _i < count; _i++) {
msg.push(noise);
}
msg = msg.join(sep);
let accept = req.headers["accept"];
if (/json/.test(accept)) {
res.setHeader("content-type", "application/json");
response = JSON.stringify({
result: msg
});
}
res.end(response);
} else if (!req.body) {
let buf = "";
req.on("data", onData);
req.on("end", onEnd);
function onData (data) {
buf += data;
}
function onEnd () {
let body, response;
let contentType = req.headers["content-type"];
if (/json/.test(contentType)) {
body = JSON.parse(buf);
} else {
res.writeHead(400, "This endpoint only accepts JSON POST bodies");
return res.end();
}
let count = body.count || 1;
let noise = body.noise.toUpperCase();
let sep = body.sep || " ";
if (noise === void 0) {
res.writeHead(400, "Invalid request: 'noise' property required");
}
let msg = [];
for (let _i = 0; _i < count; _i++) {
msg.push(noise);
}
msg = msg.join(sep);
let accept = req.headers["accept"];
if (/json/.test(accept)) {
res.setHeader("content-type", "application/json");
response = JSON.stringify({
result: msg
});
}
res.end(response);
}
}
}