-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
CurlHelper.js
109 lines (94 loc) · 2.77 KB
/
CurlHelper.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
export class CurlHelper {
constructor(config) {
this.request = config;
}
getHeaders() {
let headers = this.request.headers,
curlHeaders = "";
// get the headers concerning the appropriate method (defined in the global axios instance)
if (headers.hasOwnProperty("common")) {
headers = this.request.headers[this.request.method];
}
// add any custom headers (defined upon calling methods like .get(), .post(), etc.)
for(let property in this.request.headers) {
if (
!["common", "delete", "get", "head", "patch", "post", "put"].includes(
property
)
) {
headers[property] = this.request.headers[property];
}
}
for(let property in headers) {
if({}.hasOwnProperty.call(headers, property) && headers[property]) {
let header = `${property}:${headers[property]}`;
curlHeaders = `${curlHeaders} -H '${header}'`;
}
}
return curlHeaders.trim();
}
getMethod() {
return `-X ${this.request.method.toUpperCase()}`;
}
getBody() {
if (
typeof this.request.data !== "undefined" &&
this.request.data !== "" &&
this.request.data !== null &&
this.request.method.toUpperCase() !== "GET"
) {
let data =
typeof this.request.data === "object" ||
Object.prototype.toString.call(this.request.data) === "[object Array]"
? JSON.stringify(this.request.data)
: this.request.data;
return `--data '${data}'`.trim();
} else {
return "";
}
}
getUrl() {
if (this.request.baseURL) {
let baseUrl = this.request.baseURL
let url = this.request.url
let finalUrl = baseUrl + "/" + url
return finalUrl
.replace(/\/{2,}/g, '/')
.replace("http:/", "http://")
.replace("https:/", "https://")
}
return this.request.url;
}
getQueryString() {
if (this.request.paramsSerializer) {
const params = this.request.paramsSerializer(this.request.params)
if (!params || params.length === 0) return ''
if (params.startsWith('?')) return params
return `?${params}`
}
let params = ""
let i = 0
for(let param in this.request.params) {
if({}.hasOwnProperty.call(this.request.params, param)) {
params +=
i !== 0
? `&${param}=${this.request.params[param]}`
: `?${param}=${this.request.params[param]}`;
i++;
}
}
return params;
}
getBuiltURL() {
let url = this.getUrl();
if (this.getQueryString() !== "") {
url += this.getQueryString();
}
return url.trim();
}
generateCommand() {
return `curl ${this.getMethod()} "${this.getBuiltURL()}" ${this.getHeaders()} ${this.getBody()}`
.trim()
.replace(/\s{2,}/g, " ");
}
}