-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathconverter-v2-to-v1.js
More file actions
838 lines (701 loc) · 29.3 KB
/
converter-v2-to-v1.js
File metadata and controls
838 lines (701 loc) · 29.3 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
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
/* eslint-disable object-shorthand */
var _ = require('lodash').noConflict(),
util = require('../../util'),
v2Common = require('../../common/v2'),
Builders = function (options) {
this.options = options || {};
};
_.assign(Builders.prototype, {
/**
* Converts v2 style auth manifests into their v1 equivalents.
*
* @param {Object} entityV2 - The v1 auth manifest to be transformed into v1.
* @param {?Object} options - The set of options for the current auth cleansing operation.
* @param {?Boolean} [options.excludeNoauth=false] - When set to true, noauth is set to null.
*
* @returns {Object} The transformed auth object.
*/
auth: function (entityV2, options) {
return util.authMapToArray(entityV2, options);
},
/**
* Constructs a V1 "events" object from a V2 Postman entity
*
* @param {Object} entityV2 - The v2 event object to be converted.
* @returns {Object[]} - The resultant v1 script definition.
*/
events: function (entityV2) {
// events is treated as the source of truth in v1, so handle that first and bail out.
var source = entityV2.events || entityV2.event;
if (_.isArray(source)) {
// @todo: Improve this to order prerequest events before test events
_.forEach(source, function (event) {
!event.listen && (event.listen = 'test');
if (event.script) {
!event.script.type && (event.script.type = 'text/javascript');
// @todo: Add support for src
_.isString(event.script.exec) && (event.script.exec = event.script.exec.split('\n'));
}
});
return source;
}
},
/**
* Facilitates sanitized variable transformations across all levels for v1 collection normalization.
*
* @param {Object} entity - The wrapper object containing variable definitions.
* @param {?Object} options - The set of options for the current variable transformation.
* @param {?Object} options.fallback - The set of fallback values to be applied when no variables exist.
* @param {?Boolean} options.noDefaults - When set to true, no defaults are applied.
* @param {?Boolean} options.retainIds - When set to true, ids are left as is.
* @returns {Object[]} - The set of sanitized variables.
*/
variables: function (entity, options) {
return util.handleVars(entity, options);
},
/**
* Extracts all subfolders from a v2.0.0 collection or folder
*
* @param {Object} folderOrCollection - Thw entity to extract child items from.
* @returns {Object[]} - The list of extracted folder items.
*/
extractFolderItems: function (folderOrCollection) {
if (!folderOrCollection) { return; }
var i,
self = this,
folders = [],
items = folderOrCollection.item || folderOrCollection.items;
!_.isArray(items) && (items = [items]);
for (i = 0; i < items.length; i++) {
if (items[i] && (items[i].items || items[i].item)) {
folders.push(items[i]);
folders = [].concat(folders, self.extractFolderItems(items[i]));
}
}
return folders;
},
/**
* Extracts all requests from a v2.0.0 collection or folder
*
* @param {Object} folderOrCollection - The object to extract sub-items from.
* @returns {Object[]} - The list of extracted folder items.
*/
extractItems: function (folderOrCollection) {
if (!folderOrCollection) { return; }
var i,
self = this,
requests = [],
isFolder,
items = folderOrCollection.item || folderOrCollection.items;
!_.isArray(items) && (items = [items]);
for (i = 0; i < items.length; i++) {
isFolder = items[i] && (items[i].items || items[i].item);
if (items[i]) {
isFolder ? (requests = [].concat(requests, self.extractItems(items[i]))) : requests.push(items[i]);
}
}
return requests;
},
/**
* Constructs a monolithic raw HTTP header block from a V2 header array
*
* @param {Object} item - The wrapper object to extract headers from.
* @returns {*|string} - The resultant header string.
*/
headers: function (item) {
if (!(item && item.request)) { return; }
return _.map(item.request.headers || item.request.header, function (header) {
return (header.disabled ? '// ' : '') + header.key + ': ' + header.value;
}).join('\n');
},
/**
* Detects the data mode from a given Postman Collection V2 item
*
* @param {Object} item - .
* @returns {*|number|string}
*/
dataMode: function (item) {
return v2Common.modeMap[_.get(item, 'request.body.mode')];
},
/**
* Returns the appropriate request data based on the data mode.
*
* @param {Object} item - The .
* @returns {Object} - The converted request body.
*/
data: function (item) {
var self = this,
mode = _.get(item, 'request.body.mode'),
retainEmpty = this.options.retainEmptyValues;
if (mode === 'raw' || mode === 'file' || mode === 'graphql' || !mode) {
return retainEmpty ? null : undefined;
}
return _.map(item.request.body[mode], function (elem) {
// Only update the value in v1 if src in v2 is non-empty
if (elem && elem.type === 'file' && _.has(elem, 'src')) {
elem.value = (_.isString(elem.src) || _.isArray(elem.src)) ? elem.src : null;
delete elem.src;
}
// Prevents empty request body descriptions from showing up in the result, keeps collections clean.
elem.description = self.description(elem.description);
_.has(elem, 'disabled') && (elem.enabled = !elem.disabled);
delete elem.disabled;
return elem;
});
},
/**
* In case of raw request bodies, this constructs the proper raw data from a V2 item.
*
* @param {Object} item - The v2 request to derive body information from.
* @returns {String} - The inferred v1 request body mode.
*/
rawModeData: function (item) {
var mode = _.get(item, 'request.body.mode');
if (mode === 'raw') {
return item.request.body.raw;
}
else if (mode === 'file') {
return _.get(item.request.body, 'file.src');
}
return this.options.retainEmptyValues ? null : undefined;
},
/**
* Returns GraphQL data if mode is set to graphql.
*
* @param {Object} item - The v2 request to derive information form.
* @returns {Object} - GraphQL request body.
*/
graphqlModeData: function (item) {
var mode = _.get(item, 'request.body.mode');
if (mode === 'graphql') {
return item.request.body.graphql;
}
return this.options.retainEmptyValues ? null : undefined;
},
/**
* Creates options for body from v2 format.
*
* @param {Object} item - The v2 request to derive information form.
* @returns {Object} - The converted body options.
*/
dataOptions: function (item) {
var options = _.get(item, 'request.body.options'),
bodyOptions = {},
mode;
if (!options) {
return;
}
// Convert v2 mode to v1 mode
for (mode in v2Common.modeMap) {
if (!_.isEmpty(options[mode])) {
bodyOptions[v2Common.modeMap[mode]] = options[mode];
}
}
return _.isEmpty(bodyOptions) ? undefined : bodyOptions;
},
/**
* Creates an object of path-variables and their values from a V2 item
*
* @param {Object} item - The wrapper object containing path variable information.
* @returns {Object} - The resultant hash of path variables.
*/
pathVariables: function (item) {
var variable = _.get(item, 'request.url.variables') || _.get(item, 'request.url.variable');
if (!variable) { return; }
return _.transform(variable, function (accumulator, v) {
accumulator[v.key || v.id] = v.value; // v2.0.0 supports both key and id, v2.1.0 will drop id support
}, {});
},
/**
* Creates a V1 URL from a V2 item
*
* @param {Object} item - The v2 request to extract the URL from.
* @returns {String} - The extracted URL of the request.
*/
url: function (item) {
var url = _.get(item, 'request.url');
if (_.isString(url)) {
return url;
}
if (!url) {
return '';
}
return util.urlunparse(url);
},
/**
* Extracts test from a V2 collection
*
* @param {Object} item - The wrapper object to extract test code from.
* @returns {String} - The resultant test script code.
*/
tests: function (item) {
var allEvents = item.events || item.event,
events;
// Nothing to do if the item has no associated events
if (!allEvents) {
return;
}
events = _.filter(allEvents, { listen: 'test' });
return _.map(events, function (event) {
var tests = _.get(event, 'script.exec');
// @todo: Possible dead code, remove when confirmed
if (_.isArray(tests)) {
tests = tests.join('\n');
}
return tests;
}).join('\n');
},
/**
* Extracts the pre-request script from an Item
*
* @param {Object} item - The wrapper object to extract pre-request code from.
* @returns {String} - The resultant pre-request script code.
*/
preRequestScript: function (item) {
var allEvents = item.events || item.event,
events;
// Nothing to do if the item has no associated events
if (!allEvents) {
return;
}
events = _.filter(allEvents, { listen: 'prerequest' });
return _.map(events, function (event) {
var tests = _.get(event, 'script.exec');
// @todo: Possible dead code, remove when confirmed
if (_.isArray(tests)) {
tests = tests.join('\n');
}
return tests;
}).join('\n');
},
/**
* Converts a V2 cookie to a V1 cookie.
*
* @param {Object} cookieV2 - The v2 cookie object to be converted.
* @returns {{expirationDate: *, hostOnly: *, httpOnly: *,
* domain: (any), path: (any), secure: *, session: *, value: *, name: *}}
*/
cookie: function (cookieV2) {
return {
expirationDate: cookieV2.expires,
hostOnly: cookieV2.hostOnly,
httpOnly: cookieV2.httpOnly,
domain: cookieV2.domain,
path: cookieV2.path,
secure: cookieV2.secure,
session: cookieV2.session,
value: cookieV2.value,
name: cookieV2.key || cookieV2.name
};
},
/**
* Converts a V2 response object to a V1 response
*
* @param {Object} responseV2 - The v2 response to be converted.
* @returns {Object} - The converted v1 response.
*/
response: function (responseV2) {
var self = this,
response = {},
handlePartial = self.options.handlePartial,
id = responseV2.id || responseV2._postman_id,
originalRequest = responseV2.originalRequest || responseV2.request;
// the true in the next line ensures that we don't recursively go on processing responses in a request.
response.request = originalRequest ? self.request({ request: originalRequest }, undefined, true) : undefined;
// add the requestObject to the response (needed by sync)
try {
response.request && (response.requestObject = JSON.stringify(response.request));
}
catch (e) { /* It's fine, not a fatal error, just move on. */ }
// do not attempt to regenerate response id here when `retainIds` is set to false
// if id is changed here the parent's `responses_order` also needs to be changed
// that can't be done yet
response.id = id || util.uid();
response.name = responseV2.name;
response.status = responseV2.status;
response.responseCode = {
code: responseV2.code,
name: responseV2.status,
// TODO: get a list of descriptions
detail: ''
};
response.language = responseV2._postman_previewlanguage ||
_.get(responseV2, '_.postman_previewlanguage') || 'Text';
response.previewType = responseV2._postman_previewtype ||
_.get(responseV2, '_.postman_previewtype') || 'html';
response.time = responseV2.responseTime;
response.headers = responseV2.headers || responseV2.header;
response.cookies = _.map(responseV2.cookies || responseV2.cookie, self.cookie);
response.text = responseV2.body;
response.rawDataType = 'text';
if (handlePartial) {
(!(responseV2.code || responseV2.status)) && (response.responseCode = undefined);
(responseV2.cookies === undefined) && (response.cookies = undefined);
(responseV2.body === undefined) && (
response.rawDataType =
response.language =
response.previewType = undefined
);
}
return response;
},
/**
* Extracts the array of responses from a V2 Item.
*
* @param {Object} item - The v2 item to extract saved responses from.
* @returns {Object[]} - The list of saved response objects for the current request.
*/
responses: function (item) {
var self = this,
allResponses = item.responses || item.response;
if (!allResponses) { return; }
return _.map(allResponses, function (response) {
return self.response(response, item);
});
},
/**
* Creates an ordering field for responses of a V2 Item.
*
* @param {Object} item - The v2 item to extract saved responses from.
* @returns {Object[]} - The order of responses within the V2 Item.
*/
responses_order: function (item) {
var allResponses = item.responses || item.response;
if (!allResponses) {
return [];
}
return _.map(allResponses, 'id');
},
/**
* Converts a V2 request to a V1 request.
*
* @param {Object} item - The v2 item to be converted.
* @param {Object} collectionId - The collection id related to the current conversion routine.
* @param {Boolean} [skipResponses=false] - When set to true, excludes saved responses from the result.
* @returns {{id: *, name: *, description: (*|string|builders.description), url: *, collectionId: *, method: *,
* currentHelper: *, helperAttributes: *}|*}
*/
request: function (item, collectionId, skipResponses) {
if (!item) { return; }
var units = ['headers', 'dataMode', 'data', 'rawModeData', 'graphqlModeData',
'pathVariables', 'tests', 'preRequestScript', 'url', 'dataOptions'],
self = this,
request,
description,
currentHelper,
helperAttributes,
req = item && item.request,
v2Auth = req && req.auth,
auth = self.auth(req),
events = self.events(item),
variables = self.variables(item, { retainIds: self.options.retainIds }),
url = req && req.url,
retainEmpty = self.options.retainEmptyValues,
allowAuthReset = _.get(self.options, 'allowFieldResets', []).includes('auth'),
allowDescriptionReset = _.get(self.options, 'allowFieldResets', []).includes('description'),
handlePartial = self.options.handlePartial,
urlObj = _.isString(url) ? util.urlparse(url) : url,
headers = req && (req.headers || req.header),
pathVariables = urlObj && (urlObj.variables || urlObj.variable);
if (!skipResponses) {
units.push('responses');
units.push('responses_order');
}
if (v2Auth && v2Auth.type) {
// @todo: Add support for custom auth helpers
currentHelper = v2Common.authMap[v2Auth.type];
if (util.authMappersFromCurrent[currentHelper]) {
_.isArray(v2Auth[v2Auth.type]) && (v2Auth = util.authArrayToMap(req));
helperAttributes = util.authMappersFromCurrent[currentHelper](v2Auth[v2Auth.type]);
}
else {
helperAttributes = null;
}
}
else if (v2Auth === null) {
currentHelper = null;
helperAttributes = null;
}
request = {
// do not attempt to regenerate request id here when `retainIds` is set to false
// if id is changed here the parent's `order` also needs to be changed
// that can't be done yet
id: item.id || item._postman_id || util.uid(),
name: item.name,
collectionId: collectionId,
method: item.request ? item.request.method : undefined,
currentHelper: currentHelper,
helperAttributes: helperAttributes
};
// add protocolProfileBehavior property from item to the request
util.addProtocolProfileBehavior(item, request);
// only include the dataDisabled flag if truthy
if (req && req.body && _.has(req.body, 'disabled') && (req.body.disabled || retainEmpty)) {
request.dataDisabled = Boolean(req.body.disabled);
}
description = item.request && self.description(item.request.description);
// Prevent empty request descriptions from showing up in the converted result, keeps collections clean.
if (description) { request.description = description; }
else if (retainEmpty || allowDescriptionReset && item.request.description === null) { request.description = null; }
if(allowAuthReset && auth === null){
request.auth = null;
} else (auth || (auth === null)) && (request.auth = auth);
events && events.length && (request.events = events);
variables && variables.length && (request.variables = variables);
_.forEach(units, function (unit) {
request[unit] = self[unit](item);
});
// description transformations for v2 to v1
urlObj && (request.pathVariableData = _.map(pathVariables, function (v) {
var result = { key: v.key || v.id, value: v.value };
// Prevent empty path variable descriptions from showing up in converted results, keeps collections clean.
if (v.description) { result.description = self.description(v.description); }
else if (retainEmpty) { result.description = null; }
return result;
}));
urlObj && (request.queryParams = _.map(urlObj.query, function (queryParam) {
// Prevents empty query param descriptions from showing up in the result, keeps collections clean.
queryParam.description = self.description(queryParam.description);
_.has(queryParam, 'disabled') && (queryParam.enabled = !queryParam.disabled);
delete queryParam.disabled;
return queryParam;
}));
// item truthiness is already validated by this point
request.headerData = _.map(headers, function (header) {
// Prevents empty query param descriptions from showing up in the result, keeps collections clean.
header.description = self.description(header.description);
_.has(header, 'disabled') && (header.enabled = !header.disabled);
delete header.disabled;
return header;
});
// In case of a partial transformation, remove undefined fields
if (handlePartial) {
(headers === undefined) && (request.headers = request.headerData = undefined);
(item.responses === undefined) && (request.responses = request.responses_order = undefined);
(url === undefined) && (request.url = request.pathVariableData = request.queryParams = undefined);
}
return request;
},
/**
* Creates a V1 compatible array of requests from a Postman V2 collection.
*
* @param {Object} collectionV2 - The v2 collection to derive v1 requests from.
* @returns {Object[]} - The list of v1 request objects.
*/
requests: function (collectionV2) {
var self = this,
requests = [],
info = collectionV2 && collectionV2.info,
id = info && (info.id || info._postman_id) || collectionV2.id;
_.forEach(self.extractItems(collectionV2), function (item) {
var requestV1 = self.request(item, id);
requests.push(requestV1);
});
return requests;
},
/**
* Creates a V1 compatible array of solo requestIds from a Postman collection V2
*
* @param {Object} collectionV2 - The v2 collection to be used for request order derivation.
* @returns {Object[]} - The request order for the resultant v1 collection.
*/
order: function (collectionV2) {
var itemArray = collectionV2.items || collectionV2.item,
allItems = _.isArray(itemArray) ? itemArray : [itemArray];
// eslint-disable-next-line lodash/prefer-compact
return _.filter(_.map(allItems, function (item) {
if (!item) { return; }
var isFolder = (item.items || item.item);
if (!isFolder) {
return item.id || item._postman_id;
}
}));
},
/**
* Creates a V1 compatible array of folder orders from a Postman collection V2
*
* @param {Object} folderOrCollection - The object to derive folder order details from.
* @returns {Object[]} - The list of folder ids that indicate the order.
*/
folders_order: function (folderOrCollection) {
var itemArray = folderOrCollection.items || folderOrCollection.item,
allItems = _.isArray(itemArray) ? itemArray : [itemArray];
// eslint-disable-next-line lodash/prefer-compact
return _.filter(_.map(allItems, function (item) {
if (!item) { return; }
var isFolder = (item.items || item.item);
if (isFolder) {
return item.id || item._postman_id;
}
}));
},
/**
* Creates an array of V1 compatible folders from a V2 collection
*
* @param {Object} collectionV2 - The v2 collection to derive folder structure information from.
* @returns {Object[]} - The list of folder definitions.
*/
folders: function (collectionV2) {
var self = this,
retainEmpty = self.options.retainEmptyValues;
return _.map(self.extractFolderItems(collectionV2), function (folder) {
if (!folder) { return; }
var folderItems = folder.items || folder.item,
description = self.description(folder.description),
auth = self.auth(folder),
events = self.events(folder),
variables = self.variables(folder, { retainIds: self.options.retainIds }),
result = {
// do not attempt to regenerate folder id here when `retainIds` is set to false
// if id is changed here the parent's `folder_order` also needs to be changed
// that can't be done yet
id: folder.id || folder._postman_id || util.uid(),
name: folder.name,
// eslint-disable-next-line lodash/prefer-compact
order: _.filter(_.map(folderItems, function (f) {
if (!f) { return; }
var isFolder = (f.items || f.item);
return !isFolder && (f.id || f._postman_id);
})),
folders_order: self.folders_order(folder)
};
((auth && auth.type) || (auth === null)) && (result.auth = auth);
events && events.length && (result.events = events);
variables && variables.length && (result.variables = variables);
util.addProtocolProfileBehavior(folder, result);
// Prevent empty folder descriptions from showing up in the result, keeps collections clean.
if (description) { result.description = description; }
else if (retainEmpty) { result.description = null; }
return result;
});
},
/**
* Creates the v1.0.0 compatible description string from the v2.0.0 description format.
*
* @param {Object} descriptionV2 - The v2 style description to be converted
*
* @returns {String} - The resultant v1 description.
*/
description: function (descriptionV2) {
var description,
retainEmpty = this.options.retainEmptyValues;
allowReset = _.get(this.options, 'allowFieldResets', []).includes('description')
description = _.isObject(descriptionV2) ? descriptionV2.content : descriptionV2;
if (description) {
return description;
} else if (retainEmpty || (allowReset && descriptionV2 === null)) {
return null;
}
}
});
module.exports = {
input: '2.0.0',
output: '1.0.0',
Builders: Builders,
/**
* Converts a single V2 item to a V1 request.
*
* @param {Object} request - The request to be converted.
* @param {Object} options - The set of options for request conversion.
* @param {Function} callback - The function to be invoked after conversion has completed.
*/
convertSingle: function (request, options, callback) {
var builders = new Builders(options),
clone = _.cloneDeep(request),
converted,
err;
try {
clone = v2Common.populateIds(clone);
converted = builders.request(clone);
}
catch (e) {
err = e;
}
if (callback) {
return callback(err, converted);
}
if (err) {
throw err;
}
return converted;
},
/**
* Converts a single V2 item to a V1 request.
*
* @param {Object} response - The response to be converted.
* @param {Object} options - The set of options for request conversion.
* @param {Function} callback - The function to be invoked after conversion has completed.
*/
convertResponse: function (response, options, callback) {
var builders = new Builders(options),
converted,
err;
try {
converted = builders.response(_.cloneDeep(response));
}
catch (e) {
err = e;
}
if (callback) {
return callback(err, converted);
}
if (err) {
throw err;
}
return converted;
},
/**
* Converts a V2 collection to a V1 collection (performs ID replacement, etc as necessary).
*
* @param {Object} collection - The collection to be converted.
* @param {Object} options - The set of options for request conversion.
* @param {Function} callback - The function to be invoked after conversion has completed.
*/
convert: function (collection, options, callback) {
collection = _.cloneDeep(collection);
var auth,
events,
variables,
builders = new Builders(options),
authOptions = { excludeNoauth: true },
varOpts = options && { fallback: options.env, retainIds: options.retainIds },
units = ['order', 'folders_order', 'folders', 'requests'],
id = _.get(collection, 'info._postman_id') || _.get(collection, 'info.id'),
info = collection && collection.info,
newCollection = {
id: id && options && options.retainIds ? id : util.uid(),
name: info && info.name
};
// ensure that each item has an ID
collection = v2Common.populateIds(collection);
try {
// eslint-disable-next-line max-len
newCollection.description = builders.description(info && info.description);
(auth = builders.auth(collection, authOptions)) && (newCollection.auth = auth);
(events = builders.events(collection)) && (newCollection.events = events);
(variables = builders.variables(collection, varOpts)) && (newCollection.variables = variables);
util.addProtocolProfileBehavior(collection, newCollection);
units.forEach(function (unit) {
newCollection[unit] = builders[unit](collection);
});
}
catch (e) {
if (callback) {
return callback(e, null);
}
throw e;
}
if (options && options.handlePartial) {
(!collection.item) && (
newCollection.requests =
newCollection.folders =
newCollection.folders_order =
newCollection.order = undefined
);
}
if (callback) {
return callback(null, newCollection);
}
return newCollection;
}
};