Repository navigation
Expand file tree
/
Copy pathhelper.js
More file actions
118 lines (101 loc) · 2.73 KB
/
Copy pathhelper.js
File metadata and controls
118 lines (101 loc) · 2.73 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
const Handlebars = require('handlebars');
const { sjs, attr } = require("slow-json-stringify");
const GREETING = "Hello, World!";
const headerTypes = {
plain: 'text/plain',
json: 'application/json',
html: 'text/html; charset=UTF-8'
};
function sortByMessage(arr) {
const n = arr.length;
for (let i = 1; i < n; i++) {
const c = arr[i];
let j = i - 1;
while (j > -1 && c.message < arr[j].message) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = c;
}
return arr;
}
function generateRandomNumber(){
return Math.ceil(Math.random() * 10000);
}
const jsonSerializer = sjs({ message: attr("string") });
const worldObjectSerializer = sjs({ id: attr("number"), randomnumber: attr("number")});
const escapeHTMLRules = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '/': '/' }
const unsafeHTMLMatcher = /[&<>"'\/]/g
function escapeHtmlFromText(text) {
if (unsafeHTMLMatcher.test(text) === false) return text;
return text.replace(unsafeHTMLMatcher, function (m) { return escapeHTMLRules[m] || m; });
}
function writeResponse(res, text, type = headerTypes["json"]) {
res.writeHead(200, {
"content-type": type,
server: "Node",
});
res.end(text);
}
const self = (module.exports = {
sortByMessage,
generateRandomNumber,
jsonSerializer,
worldObjectSerializer,
escapeHtmlFromText,
writeResponse,
headerTypes,
additionalFortune: () => ({
id: 0,
message: "Additional fortune added at request time.",
}),
fortunesTemplate: Handlebars.compile(
[
"<!DOCTYPE html>",
"<html>",
"<head><title>Fortunes</title></head>",
"<body>",
"<table>",
"<tr>",
"<th>id</th>",
"<th>message</th>",
"</tr>",
"{{#fortunes}}",
"<tr>",
"<td>{{id}}</td>",
"<td>{{message}}</td>",
"</tr>",
"{{/fortunes}}",
"</table>",
"</body>",
"</html>",
].join("")
),
randomTfbNumber: () => Math.floor(Math.random() * 10000) + 1,
fillArray: (value, len) => {
const arr = [];
for (let i = 0; i < len; i++) {
arr.push(value);
}
return arr;
},
addTfbHeaders: (res, headerType) => {
res.setHeader('Server', 'Node');
res.setHeader('Content-Type', headerTypes[headerType]);
},
responses: {
jsonSerialization: (req, res) => {
writeResponse(res, jsonSerializer({ message: GREETING }));
},
plaintext: (req, res) => {
writeResponse(res, GREETING, headerTypes['plain']);
},
routeNotImplemented: (req, res) => {
res.writeHead(501, { "Content-Type": "text/plain; charset=UTF-8" });
const reason = {
reason: "`" + req.url + "` is not an implemented route",
};
res.end(JSON.stringify(reason));
},
},
});