-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathcode-samples.ts
392 lines (338 loc) · 13.2 KB
/
code-samples.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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import {
isCSV,
isFormData,
isFormUrlEncoded,
isGraphQL,
isPDF,
isPlainObject,
isText,
isXML,
} from './contentTypeChecks';
import { stringifyOpenAPI } from './stringifyOpenAPI';
export interface CodeSampleInput {
method: string;
url: string;
headers?: Record<string, string>;
body?: any;
}
interface CodeSampleGenerator {
id: string;
label: string;
syntax: string;
generate: (operation: CodeSampleInput) => string;
}
export const codeSampleGenerators: CodeSampleGenerator[] = [
{
id: 'curl',
label: 'cURL',
syntax: 'bash',
generate: ({ method, url, headers, body }) => {
const separator = ' \\\n';
const lines: string[] = ['curl -L'];
if (method.toUpperCase() !== 'GET') {
lines.push(`--request ${method.toUpperCase()}`);
}
lines.push(`--url '${url}'`);
if (body) {
const bodyContent = BodyGenerators.getCurlBody(body, headers);
if (bodyContent) {
body = bodyContent.body;
headers = bodyContent.headers;
}
}
if (headers && Object.keys(headers).length > 0) {
Object.entries(headers).forEach(([key, value]) => {
lines.push(`--header '${key}: ${value}'`);
});
}
if (body) {
if (Array.isArray(body)) {
lines.push(...body);
} else {
lines.push(body);
}
}
return lines.map((line, index) => (index > 0 ? indent(line, 2) : line)).join(separator);
},
},
{
id: 'javascript',
label: 'JavaScript',
syntax: 'javascript',
generate: ({ method, url, headers, body }) => {
let code = '';
if (body) {
const lines = BodyGenerators.getJavaScriptBody(body, headers);
if (lines) {
// add the generated code to the top
code += lines.code;
body = lines.body;
headers = lines.headers;
}
}
code += `const response = await fetch('${url}', {
method: '${method.toUpperCase()}',\n`;
if (headers && Object.keys(headers).length > 0) {
code += indent(`headers: ${stringifyOpenAPI(headers, null, 2)},\n`, 4);
}
if (body) {
code += indent(`body: ${body}\n`, 4);
}
code += '});\n\n';
code += 'const data = await response.json();';
return code;
},
},
{
id: 'python',
label: 'Python',
syntax: 'python',
generate: ({ method, url, headers, body }) => {
let code = 'import requests\n\n';
if (body) {
const lines = BodyGenerators.getPythonBody(body, headers);
// add the generated code to the top
if (lines) {
code += lines.code;
body = lines.body;
headers = lines.headers;
}
}
code += `response = requests.${method.toLowerCase()}(\n`;
code += indent(`"${url}",\n`, 4);
if (headers && Object.keys(headers).length > 0) {
code += indent(`headers=${stringifyOpenAPI(headers)},\n`, 4);
}
const contentType = headers?.['Content-Type'] || '';
if (body) {
if (body === 'files') {
code += indent(`files=${body}\n`, 4);
} else if (contentType === 'application/json') {
// If the content type is JSON, we use json={}
code += indent(`json=${stringifyOpenAPI(body)}\n`, 4);
} else {
code += indent(`data=${stringifyOpenAPI(body)}\n`, 4);
}
}
code += ')\n\n';
code += 'data = response.json()';
return code;
},
},
{
id: 'http',
label: 'HTTP',
syntax: 'bash',
generate: ({ method, url, headers = {}, body }: CodeSampleInput) => {
const { host, path } = parseHostAndPath(url);
if (body) {
// if we had a body add a content length header
const bodyContent = body ? stringifyOpenAPI(body) : '';
// handle unicode chars with a text encoder
const encoder = new TextEncoder();
const bodyString = BodyGenerators.getHTTPBody(body, headers);
if (bodyString) {
body = bodyString;
}
headers = {
...headers,
'Content-Length': encoder.encode(bodyContent).length.toString(),
};
}
if (!headers.hasOwnProperty('Accept')) {
headers.Accept = '*/*';
}
const headerString = headers
? `${Object.entries(headers)
.map(([key, value]) =>
key.toLowerCase() !== 'host' ? `${key}: ${value}` : ''
)
.join('\n')}\n`
: '';
const bodyString = body ? `\n${body}` : '';
const httpRequest = `${method.toUpperCase()} ${decodeURI(path)} HTTP/1.1
Host: ${host}
${headerString}${bodyString}`;
return httpRequest;
},
},
];
function indent(code: string, spaces: number) {
const indent = ' '.repeat(spaces);
return code
.split('\n')
.map((line) => (line ? indent + line : ''))
.join('\n');
}
export function parseHostAndPath(url: string) {
try {
const urlObj = new URL(url);
const path = urlObj.pathname || '/';
return { host: urlObj.host, path };
} catch (_e) {
// If the URL was invalid do our best to parse the URL.
// Check for the protocol part and pull it off to grab the host
const splitted = url.split('//');
const fullUrl = splitted[1] ? splitted[1] : url;
// separate paths from the first element (host)
const parts = fullUrl.split('/');
// pull off the host (mutates)
const host = parts.shift();
// add a leading slash and join the paths again
const path = `/${parts.join('/')}`;
return { host, path };
}
}
// Body Generators
const BodyGenerators = {
getCurlBody(body: any, headers?: Record<string, string>) {
if (!body || !headers) return undefined;
// Copy headers to avoid mutating the original object
const headersCopy = { ...headers };
const contentType: string = headersCopy['Content-Type'] || '';
if (isFormData(contentType)) {
body = isPlainObject(body)
? Object.entries(body).map(([key, value]) => `--form '${key}=${String(value)}'`)
: `--form 'file=@${body}'`;
} else if (isFormUrlEncoded(contentType)) {
body = isPlainObject(body)
? `--data '${Object.entries(body)
.map(([key, value]) => `${key}=${String(value)}`)
.join('&')}'`
: String(body);
} else if (isText(contentType)) {
body = `--data '${String(body).replace(/"/g, '')}'`;
} else if (isXML(contentType) || isCSV(contentType)) {
// We use --data-binary to avoid cURL converting newlines to \r\n
body = `--data-binary $'${stringifyOpenAPI(body).replace(/"/g, '')}'`;
} else if (isGraphQL(contentType)) {
body = `--data '${stringifyOpenAPI(body)}'`;
// Set Content-Type to application/json for GraphQL, recommended by GraphQL spec
headersCopy['Content-Type'] = 'application/json';
} else if (isPDF(contentType)) {
// We use --data-binary to avoid cURL converting newlines to \r\n
body = `--data-binary '@${String(body)}'`;
} else {
body = `--data '${stringifyOpenAPI(body, null, 2)}'`;
}
return {
body,
headers: headersCopy,
};
},
getJavaScriptBody: (body: any, headers?: Record<string, string>) => {
if (!body || !headers) return;
let code = '';
// Copy headers to avoid mutating the original object
const headersCopy = { ...headers };
const contentType: string = headersCopy['Content-Type'] || '';
// Use FormData for file uploads
if (isFormData(contentType)) {
code += 'const formData = new FormData();\n\n';
if (isPlainObject(body)) {
Object.entries(body).forEach(([key, value]) => {
code += `formData.append("${key}", "${String(value)}");\n`;
});
} else if (typeof body === 'string') {
code += `formData.append("file", "${body}");\n`;
}
code += '\n';
body = 'formData';
} else if (isFormUrlEncoded(contentType)) {
// Use URLSearchParams for form-urlencoded data
code += 'const params = new URLSearchParams();\n\n';
if (isPlainObject(body)) {
Object.entries(body).forEach(([key, value]) => {
code += `params.append("${key}", "${String(value)}");\n`;
});
}
code += '\n';
body = 'params.toString()';
} else if (isGraphQL(contentType)) {
if (isPlainObject(body)) {
Object.entries(body).forEach(([key, value]) => {
code += `const ${key} = \`\n${indent(String(value), 4)}\`;\n\n`;
});
body = `JSON.stringify({ ${Object.keys(body).join(', ')} })`;
// Set Content-Type to application/json for GraphQL, recommended by GraphQL spec
headersCopy['Content-Type'] = 'application/json';
} else {
code += `const query = \`\n${indent(String(body), 4)}\`;\n\n`;
body = 'JSON.stringify(query)';
}
} else if (isCSV(contentType)) {
code += 'const csv = `\n';
code += indent(String(body), 4);
code += '`;\n\n';
body = 'csv';
} else if (isPDF(contentType)) {
// Use FormData to upload PDF files
code += 'const formData = new FormData();\n\n';
code += `formData.append("file", "${body}");\n\n`;
body = 'formData';
} else if (isXML(contentType)) {
code += 'const xml = `\n';
code += indent(String(body), 4);
code += '`;\n\n';
body = 'xml';
} else if (isText(contentType)) {
body = stringifyOpenAPI(body, null, 2);
} else {
body = `JSON.stringify(${stringifyOpenAPI(body, null, 2)})`;
}
return { body, code, headers: headersCopy };
},
getPythonBody: (body: any, headers?: Record<string, string>) => {
if (!body || !headers) return;
let code = '';
// Copy headers to avoid mutating the original object
const headersCopy = { ...headers };
const contentType: string = headersCopy['Content-Type'] || '';
if (isFormData(contentType)) {
code += 'files = {\n';
if (isPlainObject(body)) {
Object.entries(body).forEach(([key, value]) => {
code += `${indent(`"${key}": "${String(value)}",`, 4)}\n`;
});
}
code += '}\n\n';
body = 'files';
}
if (isPDF(contentType)) {
code += 'files = {\n';
code += `${indent(`"file": "${body}",`, 4)}\n`;
code += '}\n\n';
body = 'files';
}
if (isGraphQL(contentType)) {
// Set Content-Type to application/json for GraphQL, recommended by GraphQL spec
headersCopy['Content-Type'] = 'application/json';
}
return { body, code, headers: headersCopy };
},
getHTTPBody: (body: any, headers?: Record<string, string>) => {
if (!body || !headers) return undefined;
const contentType: string = headers['Content-Type'] || '';
const typeHandlers = {
pdf: () => `${stringifyOpenAPI(body, null, 2)}`,
formUrlEncoded: () => {
const encoded = isPlainObject(body)
? Object.entries(body)
.map(([key, value]) => `${key}=${String(value)}`)
.join('&')
: String(body);
return `"${encoded}"`;
},
text: () => `"${String(body)}"`,
xmlOrCsv: () => `"${stringifyOpenAPI(body).replace(/"/g, '')}"`,
default: () => `${stringifyOpenAPI(body, null, 2)}`,
};
if (isPDF(contentType)) return typeHandlers.pdf();
if (isFormUrlEncoded(contentType)) return typeHandlers.formUrlEncoded();
if (isText(contentType)) return typeHandlers.text();
if (isXML(contentType) || isCSV(contentType)) {
return typeHandlers.xmlOrCsv();
}
return typeHandlers.default();
},
};