-
Notifications
You must be signed in to change notification settings - Fork 360
/
Copy pathrequest.js
314 lines (291 loc) · 9.91 KB
/
request.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
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
const _ = require('./lodash'),
sdk = require('postman-collection'),
sanitizeOptions = require('./util').sanitizeOptions,
sanitize = require('./util').sanitize,
addFormParam = require('./util').addFormParam,
parseRequest = require('./parseRequest');
var self;
/**
* returns snippet of nodejs(native) by parsing data from Postman-SDK request object
*
* @param {Object} request - Postman SDK request object
* @param {String} indentString - indentation required for code snippet
* @param {Object} options
* @returns {String} - nodejs(native) code snippet for given request object
*/
function makeSnippet (request, indentString, options) {
var nativeModule = (request.url.protocol === 'http' ? 'http' : 'https'),
snippet,
optionsArray = [],
postData = '',
url, host, query;
if (options.ES6_enabled) {
snippet = 'const ';
}
else {
snippet = 'var ';
}
if (options.followRedirect) {
snippet += `${nativeModule} = require('follow-redirects').${nativeModule};\n`;
}
else {
snippet += `${nativeModule} = require('${nativeModule}');\n`;
}
if (options.ES6_enabled) {
snippet += 'const ';
}
else {
snippet += 'var ';
}
snippet += 'fs = require(\'fs\');\n\n';
if (_.get(request, 'body.mode') && request.body.mode === 'urlencoded') {
if (options.ES6_enabled) {
snippet += 'const ';
}
else {
snippet += 'var ';
}
snippet += 'qs = require(\'querystring\');\n\n';
}
if (options.ES6_enabled) {
snippet += 'let ';
}
else {
snippet += 'var ';
}
snippet += 'options = {\n';
/**
* creating string to represent options object using optionArray.join()
* example:
* options: {
* method: 'GET',
* hostname: 'www.google.com',
* path: '/x?a=10',
* headers: {
* 'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
* }
* }
*/
// The following code handles multiple files in the same formdata param.
// It removes the form data params where the src property is an array of filepath strings
// Splits that array into different form data params with src set as a single filepath string
if (request.body && request.body.mode === 'formdata') {
let formdata = request.body.formdata,
formdataArray = [];
formdata.members.forEach((param) => {
let key = param.key,
type = param.type,
disabled = param.disabled,
contentType = param.contentType;
// check if type is file or text
if (type === 'file') {
// if src is not of type string we check for array(multiple files)
if (typeof param.src !== 'string') {
// if src is an array(not empty), iterate over it and add files as separate form fields
if (Array.isArray(param.src) && param.src.length) {
param.src.forEach((filePath) => {
addFormParam(formdataArray, key, param.type, filePath, disabled, contentType);
});
}
// if src is not an array or string, or is an empty array, add a placeholder for file path(no files case)
else {
addFormParam(formdataArray, key, param.type, '/path/to/file', disabled, contentType);
}
}
// if src is string, directly add the param with src as filepath
else {
addFormParam(formdataArray, key, param.type, param.src, disabled, contentType);
}
}
// if type is text, directly add it to formdata array
else {
addFormParam(formdataArray, key, param.type, param.value, disabled, contentType);
}
});
request.body.update({
mode: 'formdata',
formdata: formdataArray
});
}
if (request.body && request.body[request.body.mode]) {
postData += parseRequest.parseBody(request.body.toJSON(), indentString, options.trimRequestBody,
request.headers.get('Content-Type'));
}
if (request.body && !request.headers.has('Content-Type')) {
if (request.body.mode === 'file') {
request.addHeader({
key: 'Content-Type',
value: 'text/plain'
});
}
else if (request.body.mode === 'graphql') {
request.addHeader({
key: 'Content-Type',
value: 'application/json'
});
}
}
url = new sdk.Url(request.url.toString());
host = url.host ? url.host.join('.') : '';
query = url.query ? _.reduce(url.query, (accum, q) => {
accum.push(`${q.key}=${q.value}`);
return accum;
}, []) : [];
if (query.length > 0) {
query = '?' + query.join('&');
}
else {
query = '';
}
optionsArray.push(indentString + `'method': '${request.method}'`);
optionsArray.push(`${indentString}'hostname': '${sanitize(host)}'`);
if (url.port) {
optionsArray.push(`${indentString}'port': ${url.port}`);
}
optionsArray.push(`${indentString}'path': '${sanitize(url.getPathWithQuery(true))}'`);
optionsArray.push(parseRequest.parseHeader(request, indentString));
if (options.followRedirect) {
optionsArray.push(indentString + '\'maxRedirects\': 20');
}
snippet += optionsArray.join(',\n') + '\n';
snippet += '};\n\n';
if (options.ES6_enabled) {
snippet += 'const ';
}
else {
snippet += 'var ';
}
snippet += `req = ${nativeModule}.request(options, `;
if (options.ES6_enabled) {
snippet += '(res) => {\n';
snippet += indentString + 'let chunks = [];\n\n';
snippet += indentString + 'res.on("data", (chunk) => {\n';
}
else {
snippet += 'function (res) {\n';
snippet += indentString + 'var chunks = [];\n\n';
snippet += indentString + 'res.on("data", function (chunk) {\n';
}
snippet += indentString.repeat(2) + 'chunks.push(chunk);\n';
snippet += indentString + '});\n\n';
if (options.ES6_enabled) {
snippet += indentString + 'res.on("end", (chunk) => {\n';
snippet += indentString.repeat(2) + 'let body = Buffer.concat(chunks);\n';
}
else {
snippet += indentString + 'res.on("end", function (chunk) {\n';
snippet += indentString.repeat(2) + 'var body = Buffer.concat(chunks);\n';
}
snippet += indentString.repeat(2) + 'console.log(body.toString());\n';
snippet += indentString + '});\n\n';
if (options.ES6_enabled) {
snippet += indentString + 'res.on("error", (error) => {\n';
}
else {
snippet += indentString + 'res.on("error", function (error) {\n';
}
snippet += indentString.repeat(2) + 'console.error(error);\n';
snippet += indentString + '});\n';
snippet += '});\n\n';
if (request.body && !(_.isEmpty(request.body)) && postData.length) {
if (options.ES6_enabled) {
snippet += 'let ';
}
else {
snippet += 'var ';
}
snippet += `postData = ${postData};\n\n`;
if (request.method === 'DELETE') {
snippet += 'req.setHeader(\'Content-Length\', postData.length);\n\n';
}
if (request.body.mode === 'formdata') {
snippet += 'req.setHeader(\'content-type\',' +
' \'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW\');\n\n';
}
snippet += 'req.write(postData);\n\n';
}
if (options.requestTimeout) {
snippet += `req.setTimeout(${options.requestTimeout}, function() {\n`;
snippet += indentString + 'req.abort();\n';
snippet += '});\n\n';
}
snippet += 'req.end();';
return snippet;
}
/**
* Converts Postman sdk request object to nodejs native code snippet
*
* @param {Object} request - postman-SDK request object
* @param {Object} options
* @param {String} options.indentType - type for indentation eg: Space, Tab
* @param {String} options.indentCount - number of spaces or tabs for indentation.
* @param {Boolean} options.followRedirect - whether to enable followredirect
* @param {Boolean} options.trimRequestBody - whether to trim fields in request body or not
* @param {Boolean} options.ES6_enabled - whether to generate snippet with ES6 features
* @param {Number} options.requestTimeout : time in milli-seconds after which request will bail out
* @param {Function} callback - callback function with parameters (error, snippet)
*/
self = module.exports = {
/**
* Used to return options which are specific to a particular plugin
*
* @returns {Array}
*/
getOptions: function () {
return [{
name: 'Set indentation count',
id: 'indentCount',
type: 'positiveInteger',
default: 2,
description: 'Set the number of indentation characters to add per code level'
},
{
name: 'Set indentation type',
id: 'indentType',
type: 'enum',
availableOptions: ['Tab', 'Space'],
default: 'Space',
description: 'Select the character used to indent lines of code'
},
{
name: 'Set request timeout',
id: 'requestTimeout',
type: 'positiveInteger',
default: 0,
description: 'Set number of milliseconds the request should wait for a response' +
' before timing out (use 0 for infinity)'
},
{
name: 'Follow redirects',
id: 'followRedirect',
type: 'boolean',
default: true,
description: 'Automatically follow HTTP redirects'
},
{
name: 'Trim request body fields',
id: 'trimRequestBody',
type: 'boolean',
default: false,
description: 'Remove white space and additional lines that may affect the server\'s response'
},
{
name: 'Enable ES6 features',
id: 'ES6_enabled',
type: 'boolean',
default: false,
description: 'Modifies code snippet to incorporate ES6 (EcmaScript) features'
}];
},
convert: function (request, options, callback) {
if (!_.isFunction(callback)) {
throw new Error('NodeJS-Request-Converter: callback is not valid function');
}
options = sanitizeOptions(options, self.getOptions());
// String representing value of indentation required
var indentString;
indentString = options.indentType === 'Tab' ? '\t' : ' ';
indentString = indentString.repeat(options.indentCount);
return callback(null, makeSnippet(request, indentString, options));
}
};