forked from AndrianBdn/Paw-NodeHttpCodeGenerator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAxiosCodeGenerator.ts
83 lines (70 loc) · 2.34 KB
/
AxiosCodeGenerator.ts
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
declare function require(module: string): any;
declare function registerCodeGenerator(callback: Object): void;
declare interface AxiosRequest {
name: string;
url: string;
method: string;
headers: Object;
body: any;
// httpBasicAuth: Object;
// followRedirects: boolean;
// sendCookies: boolean;
// storeCookies: boolean;
// timeout: number;
}
class ParsedURL {
public schema = 'http';
public host = 'localhost';
public port = 80;
public path = '/';
constructor(url: string) {
const regexp = /(https?):\/\/([^\/:]+):?(\d*)(\/?.*)/;
const match = url.match(regexp);
if (match) {
this.schema = match[1];
this.host = match[2];
this.port =
match[3].length > 0
? +match[3]
: (() => {
if (this.schema == 'https') return 443;
return 80;
})();
this.path = match[4];
}
}
}
class AxiosCodeGenerator {
static title = 'Axios';
static fileExtension = 'js';
static languageHighlighter = 'js';
static identifier = 'cloud.lumin.AxiosCodeGenerator';
private multipleRequestNotice(request: AxiosRequest[]) {
if (request.length > 1) {
return '// Warning: requests below are going to be executed in parallel\n\n';
}
return '';
}
public generate(context: any, requests: AxiosRequest[], options) {
if (!Array.isArray(requests)) {
requests = [context.getCurrentRequest()];
}
return this.multipleRequestNotice(requests) + requests.map(this.generateRequest).join('\n');
}
private generateRequest(request: AxiosRequest) {
const headers = request.headers;
for (var key in headers) {
headers[key] = headers[key].trim();
}
const parsedUrl = new ParsedURL(request.url);
return `// request ${request.name}
axios({
method: '${request.method.toLowerCase()}',
url: '${parsedUrl.schema}://${parsedUrl.host}${parsedUrl.path}',
${Object.keys(request.body).length > 0 ? 'data: ' + request.body + ',' : ''}
${headers ? 'headers: ' + JSON.stringify(headers) + ',' : ''}
})
`;
}
}
registerCodeGenerator(AxiosCodeGenerator);