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
94 lines (82 loc) · 2.57 KB
/
Copy pathclient.ts
File metadata and controls
94 lines (82 loc) · 2.57 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
/**
* @description
* HTTP code snippet generator for native Node.js.
*
* @author
* @AhmadNassri
*
* 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 { Client } from '../../targets';
export interface NodeNativeOptions {
insecureSkipVerify?: boolean;
}
export const native: Client<NodeNativeOptions> = {
info: {
key: 'native',
title: 'HTTP',
link: 'http://nodejs.org/api/http.html#http_http_request_options_callback',
description: 'Node.js native HTTP interface',
},
convert: ({ uriObj, method, allHeaders, postData }, options = {}) => {
const { indent = ' ', insecureSkipVerify = false } = options;
const { blank, join, push, unshift } = new CodeBuilder({ indent });
const reqOpts = {
method,
hostname: uriObj.hostname,
port: uriObj.port,
path: uriObj.path,
headers: allHeaders,
...(insecureSkipVerify ? { rejectUnauthorized: false } : {}),
};
// @ts-expect-error TODO seems like a legit error
push(`const http = require('${uriObj.protocol.replace(':', '')}');`);
blank();
push(`const options = ${stringifyObject(reqOpts, { indent })};`);
blank();
push('const req = http.request(options, function (res) {');
push('const chunks = [];', 1);
blank();
push("res.on('data', function (chunk) {", 1);
push('chunks.push(chunk);', 2);
push('});', 1);
blank();
push("res.on('end', function () {", 1);
push('const body = Buffer.concat(chunks);', 2);
push('console.log(body.toString());', 2);
push('});', 1);
push('});');
blank();
switch (postData.mimeType) {
case 'application/x-www-form-urlencoded':
if (postData.paramsObj) {
unshift("const qs = require('querystring');");
push(
`req.write(qs.stringify(${stringifyObject(postData.paramsObj, {
indent: ' ',
inlineCharacterLimit: 80,
})}));`,
);
}
break;
case 'application/json':
if (postData.jsonObj) {
push(
`req.write(JSON.stringify(${stringifyObject(postData.jsonObj, {
indent: ' ',
inlineCharacterLimit: 80,
})}));`,
);
}
break;
default:
if (postData.text) {
push(`req.write(${stringifyObject(postData.text, { indent })});`);
}
}
push('req.end();');
return join();
},
};