-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhelper.js
85 lines (71 loc) · 2.38 KB
/
helper.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
const fs = require("fs");
function isEqualIgnoreCase(input1, input2) {
return input1.toLowerCase() === input2.toLowerCase();
}
function isQueryEqual(query1, query2) {
const q1 = query1.toLowerCase();
const q2 = query2.toLowerCase();
if (encodeURIComponent(q1) === q2 || q1 === encodeURIComponent(q2)) {
return true;
}
if (decodeURIComponent(q1) === q2 || q1 === decodeURIComponent(q2)) {
return true;
}
return q1 === q2;
}
function containsSameQueryParameter(queryParameterString, requestQueries) {
const queries = queryParameterString.split("&");
const foundQueries = [];
// Loop over all recieved queries
Object.keys(requestQueries).forEach(queryKey => {
for (var i = 0; i < queries.length; i++) {
const configQuery = queries[i].split("=");
const configQueryKey = configQuery[0];
const configQueryValue = configQuery[1];
// Keys are equal
if (isEqualIgnoreCase(configQueryKey, queryKey)) {
// Value is equal
if (isQueryEqual(configQueryValue, requestQueries[queryKey])) {
foundQueries.push(queryKey);
}
}
}
});
return foundQueries.length === queries.length;
}
function writeFile(httpResponse, filePath) {
if (filePath.toLowerCase().endsWith(".json")) {
return _writeFile(httpResponse, filePath, "application/json");
} else if (filePath.toLowerCase().endsWith(".html")) {
return _writeFile(httpResponse, filePath, "text/html");
} else if (filePath.toLowerCase().endsWith(".xml")) {
return _writeFile(httpResponse, filePath, "application/xml");
}
// Fallback is to write plain text
return _writeFile(httpResponse, filePath, "text/plain");
}
function _writeFile(httpResponse, filePath, type) {
fs.readFile(filePath, "utf8", function(err, data) {
httpResponse.contentType(type);
httpResponse.end(data);
});
}
function writeResponse(httpResponse, config) {
// Response code can be written
if (config.responseCode) {
httpResponse.writeHead(config.responseCode);
}
// If there is a config file set use that file
if (config.responseFile) {
return writeFile(httpResponse, config.responseFile);
} else {
// Close response if no file was given
httpResponse.end();
}
}
module.exports = {
isEqualIgnoreCase: isEqualIgnoreCase,
isQueryEqual: isQueryEqual,
writeResponse: writeResponse,
containsSameQueryParameter: containsSameQueryParameter
};