-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathresolveExpectedRequestProperties.js
72 lines (67 loc) · 2.49 KB
/
resolveExpectedRequestProperties.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
// TODO: UPSTREAM ME - or rip out and use an already modularized or upstreamed-to-messy-version of this.
var urlModule = require("url");
module.exports = function resolveExpectedRequestProperties(
expectedRequestProperties
) {
if (typeof expectedRequestProperties === "string") {
expectedRequestProperties = { url: expectedRequestProperties };
} else if (
expectedRequestProperties &&
typeof expectedRequestProperties === "object"
) {
expectedRequestProperties = Object.assign({}, expectedRequestProperties);
}
if (expectedRequestProperties) {
if (typeof expectedRequestProperties.url === "string") {
var matchMethod =
expectedRequestProperties.url.match(/^([A-Z]+) ([\s\S]*)$/);
if (matchMethod) {
expectedRequestProperties.method =
expectedRequestProperties.method || matchMethod[1];
expectedRequestProperties.url = matchMethod[2];
} else if (!expectedRequestProperties.method) {
expectedRequestProperties.method = "GET";
}
}
} else {
expectedRequestProperties = {};
}
if (/^https?:\/\//.test(expectedRequestProperties.url)) {
var urlObj = new urlModule.URL(expectedRequestProperties.url);
expectedRequestProperties.headers = expectedRequestProperties.headers || {};
if (
Object.keys(expectedRequestProperties.headers).every(function (key) {
return key.toLowerCase() !== "host";
})
) {
expectedRequestProperties.headers.Host = urlObj.host;
}
expectedRequestProperties.host =
expectedRequestProperties.host || urlObj.hostname;
if (urlObj.port && typeof expectedRequestProperties.port === "undefined") {
expectedRequestProperties.port = parseInt(urlObj.port, 10);
}
if (
urlObj.protocol === "https:" &&
typeof expectedRequestProperties.encrypted === "undefined"
) {
expectedRequestProperties.encrypted = true;
}
expectedRequestProperties.url = urlObj.pathname + urlObj.search;
}
var expectedRequestBody = expectedRequestProperties.body;
if (
Array.isArray(expectedRequestBody) ||
(expectedRequestBody && typeof expectedRequestBody === "object")
) {
expectedRequestProperties.headers = expectedRequestProperties.headers || {};
if (
Object.keys(expectedRequestProperties.headers).every(function (key) {
return key.toLowerCase() !== "content-type";
})
) {
expectedRequestProperties.headers["Content-Type"] = "application/json";
}
}
return expectedRequestProperties;
};