forked from Kong/httpsnippet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
121 lines (99 loc) · 3.4 KB
/
Copy pathclient.ts
File metadata and controls
121 lines (99 loc) · 3.4 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
/**
* @description
* HTTP code snippet generator for fetch
*
* @author
* @pmdroid
*
* for any questions or issues regarding the generated code snippet, please open an issue mentioning the author.
*/
import stringifyObject from 'stringify-object';
import { CodeBuilder } from '../../../helpers/code-builder';
import { getHeaderName } from '../../../helpers/headers';
import { Client } from '../../targets';
interface FetchOptions {
credentials?: Record<string, string> | null;
}
export const fetch: Client<FetchOptions> = {
info: {
key: 'fetch',
title: 'fetch',
link: 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch',
description: 'Perform asynchronous HTTP requests with the Fetch API',
},
convert: ({ method, allHeaders, postData, fullUrl }, inputOpts) => {
const opts = {
indent: ' ',
credentials: null,
...inputOpts,
};
const { blank, join, push } = new CodeBuilder({ indent: opts.indent });
const options: Record<string, any> = {
method,
};
if (Object.keys(allHeaders).length) {
options.headers = allHeaders;
}
if (opts.credentials !== null) {
options.credentials = opts.credentials;
}
push(`const url = '${fullUrl}';`);
switch (postData.mimeType) {
case 'application/x-www-form-urlencoded':
options.body = postData.paramsObj ? postData.paramsObj : postData.text;
break;
case 'application/json':
options.body = JSON.stringify(postData.jsonObj);
break;
case 'multipart/form-data':
if (!postData.params) {
break;
}
// The FormData API automatically adds a `Content-Type` header for `multipart/form-data` content and if we add our own here data won't be correctly transmitted.
// eslint-disable-next-line no-case-declarations -- We're only using `contentTypeHeader` within this block.
const contentTypeHeader = getHeaderName(allHeaders, 'content-type');
if (contentTypeHeader) {
delete allHeaders[contentTypeHeader];
}
push('const form = new FormData();');
postData.params.forEach(param => {
push(`form.append('${param.name}', '${param.value || param.fileName || ''}');`);
});
blank();
break;
default:
if (postData.text) {
options.body = postData.text;
}
}
// If we ultimately don't have any headers to send then we shouldn't add an empty object into the request options.
if (options.headers && !Object.keys(options.headers).length) {
delete options.headers;
}
push(
`const options = ${stringifyObject(options, {
indent: opts.indent,
inlineCharacterLimit: 80,
transform: (_, property, originalResult) => {
if (property === 'body' && postData.mimeType === 'application/x-www-form-urlencoded') {
return `new URLSearchParams(${originalResult})`;
}
return originalResult;
},
})};`,
);
blank();
if (postData.params && postData.mimeType === 'multipart/form-data') {
push('options.body = form;');
blank();
}
push('try {');
push(`const response = await fetch(url, options);`, 1);
push('const data = await response.json();', 1);
push('console.log(data);', 1);
push('} catch (error) {');
push('console.error(error);', 1);
push('}');
return join();
},
};