This repository has been archived by the owner on Aug 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
JavaScriptFetchGenerator.js
77 lines (60 loc) · 1.8 KB
/
JavaScriptFetchGenerator.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
class JavaScriptFetchGenerator {
static get identifier() {
return 'com.secretspaceagency.JavaScriptFetchGenerator';
}
static get title() {
return 'JavaScript (Fetch)';
}
static get fileExtension() {
return 'js';
}
static get languageHighlighter() {
return 'javascript';
}
getResponseTypeFromContentType(contentType = '') {
if (contentType.indexOf('json') !== -1) {
return 'json';
}
return 'text';
}
generate(context, requests) {
if (!Array.isArray(requests)) {
requests = [context.getCurrentRequest()];
}
let code = '';
for (const request of requests) {
const latestExchange = request.getLastExchange();
const contentType = latestExchange ? latestExchange.getResponseHeaderByName('Content-Type') : '';
const responseFormat = this.getResponseTypeFromContentType(contentType);
const fetchOptions = [];
if (request.method !== 'GET') {
fetchOptions.push(`method: '${request.method}'`);
}
if (Object.keys(request.headers).length > 0) {
const headerString = JSON.stringify(request.headers, null, '\t\t\t').replace(/}$/, '\t\t}');
fetchOptions.push(`headers: ${headerString}`);
}
if (request.body) {
if (request.method === 'GET' || request.method === 'HEAD') {
fetchOptions.push('// fetch does not support a body with GET or HEAD requests');
}
else {
fetchOptions.push(`body: \`${request.body}\``);
}
}
if (!request.followRedirects) {
fetchOptions.push(`redirect: 'error'`);
}
const optionsString = fetchOptions.length === 0 ? '' : `, {
${fetchOptions.join(',\n\t\t')}
}`;
code += `// ${request.name}
async function makeRequest() {
const response = await fetch('${request.url}'${optionsString});
return response.${responseFormat}();
}`;
}
return code;
}
}
registerCodeGenerator(JavaScriptFetchGenerator);