-
Notifications
You must be signed in to change notification settings - Fork 101
/
ng-swagger-gen.js
1418 lines (1328 loc) · 43 KB
/
ng-swagger-gen.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
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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/* jshint -W014 */
/* jshint -W083 */
const fs = require('fs');
const path = require('path');
const Mustache = require('mustache');
const $RefParser = require('json-schema-ref-parser');
var npmConfig = require('npm-conf');
/**
* Main generate function
*/
function ngSwaggerGen(options) {
if (typeof options.swagger != 'string') {
console.error("Swagger file not specified in the 'swagger' option");
process.exit(1);
}
if (!options.skipProxySetup) {
setupProxy();
}
$RefParser.bundle(options.swagger,
{
dereference: { circular: false },
resolve: { http: { timeout: options.timeout } }
}).then(
data => {
doGenerate(data, options);
},
err => {
console.error(
`Error reading swagger location ${options.swagger}: ${err}`
);
process.exit(1);
}
).catch(function (error) {
console.error(`Error: ${error}`);
process.exit(1);
});
}
/**
* Sets up the environment to work behind proxies.
* Uses global-agent from NodeJS >= 10,
* and global-tunnel-ng for previous versions.
*/
function setupProxy() {
var globalAgent = require('global-agent');
var globalTunnel = require('global-tunnel-ng');
var proxyAddress = getProxyAndSetupEnv();
const NODEJS_VERSION = parseInt(process.version.slice(1).split('.')[0], 10);
if (NODEJS_VERSION >= 10 && proxyAddress) {
// `global-agent` works with Node.js v10 and above.
globalAgent.bootstrap();
global.GLOBAL_AGENT.HTTP_PROXY = proxyAddress;
} else {
// `global-tunnel-ng` works only with Node.js v10 and below.
globalTunnel.initialize();
}
}
/**
* For full compatibility with globalTunnel we need to check a few places for
* the correct proxy address. Additionally we need to remove HTTP_PROXY
* and HTTPS_PROXY environment variables, if present.
* This is again for globalTunnel compatibility.
*
* This method only needs to be run when global-agent is used
*/
function getProxyAndSetupEnv() {
var proxyEnvVariableNames = [
'https_proxy',
'HTTPS_PROXY',
'http_proxy',
'HTTP_PROXY'
];
var npmVariableNames = ['https-proxy', 'http-proxy', 'proxy'];
var key;
var val;
var result;
for (var i = 0; i < proxyEnvVariableNames.length; i++) {
key = proxyEnvVariableNames[i];
val = process.env[key];
if (val) {
// Get the first non-empty
result = result || val;
// Delete all
// NB: we do it here to prevent double proxy handling
// (and for example path change)
// by us and the `request` module or other sub-dependencies
delete process.env[key];
}
}
if (!result) {
var config = npmConfig();
for (i = 0; i < npmVariableNames.length && !result; i++) {
result = config.get(npmVariableNames[i]);
}
}
return result;
}
/**
* Proceeds with the generation given the parsed swagger object
*/
function doGenerate(swagger, options) {
if (!options.templates) {
options.templates = path.join(__dirname, 'templates');
}
var output = path.normalize(options.output || 'src/app/api');
var prefix = options.prefix || 'Api';
if (swagger.swagger !== '2.0') {
console.error(
'Invalid swagger specification. Must be a 2.0. Currently ' +
swagger.swagger
);
process.exit(1);
}
swagger.paths = swagger.paths || {};
swagger.models = swagger.models || [];
var models = processModels(swagger, options);
var services = processServices(swagger, models, options);
// Apply the tag filter. If includeTags is null, uses all services,
// but still can remove unused models
const includeTags = options.includeTags;
if (typeof includeTags == 'string') {
options.includeTags = includeTags.split(',');
}
const excludeTags = options.excludeTags;
if (typeof excludeTags == 'string') {
options.excludeTags = excludeTags.split(',');
}
applyTagFilter(models, services, options);
// Read the templates
var templates = {};
var files = fs.readdirSync(options.templates);
files.forEach(function (file, index) {
var pos = file.indexOf('.mustache');
if (pos >= 0) {
var fullFile = path.join(options.templates, file);
templates[file.substr(0, pos)] = fs.readFileSync(fullFile, 'utf-8');
}
});
// read the fallback templates
var fallbackTemplates = path.join(__dirname, 'templates');
fs.readdirSync(fallbackTemplates)
.forEach(function (file) {
var pos = file.indexOf('.mustache');
if (pos >= 0) {
var fullFile = path.join(fallbackTemplates, file);
if (!(file.substr(0, pos) in templates)) {
templates[file.substr(0, pos)] = fs.readFileSync(fullFile, 'utf-8');
}
}
});
// Prepare the output folder
const modelsOutput = path.join(output, 'models');
const servicesOutput = path.join(output, 'services');
mkdirs(modelsOutput);
mkdirs(servicesOutput);
var removeStaleFiles = options.removeStaleFiles !== false;
var generateEnumModule = options.enumModule !== false;
// Utility function to render a template and write it to a file
var generate = function (template, model, file) {
var code = Mustache.render(template, model, templates)
.replace(/[^\S\r\n]+$/gm, '');
fs.writeFileSync(file, code, 'UTF-8');
console.info('Wrote ' + file);
};
// Calculate the globally used names
var moduleClass = toClassName(prefix + 'Module');
var moduleFile = toFileName(moduleClass);
// Angular's best practices demands xxx.module.ts, not xxx-module.ts
moduleFile = moduleFile.replace(/\-module$/, '.module');
var configurationClass = toClassName(prefix + 'Configuration');
var configurationInterface = toClassName(prefix + 'ConfigurationInterface');
var configurationFile = toFileName(configurationClass);
function applyGlobals(to) {
to.prefix = prefix;
to.moduleClass = moduleClass;
to.moduleFile = moduleFile;
to.configurationClass = configurationClass;
to.configurationInterface = configurationInterface;
to.configurationFile = configurationFile;
return to;
}
// Write the models and examples
var modelsArray = [];
for (var modelName in models) {
var model = models[normalizeModelName(modelName)];
if (model.modelIsEnum) {
model.enumModule = generateEnumModule;
}
applyGlobals(model);
// When the model name differs from the class name, it will be duplicated
// in the array. For example the-user would be TheUser, and would be twice.
if (modelsArray.includes(model)) {
continue;
}
modelsArray.push(model);
generate(
templates.model,
model,
path.join(modelsOutput, model.modelFile + '.ts')
);
if (options.generateExamples && model.modelExample) {
var value = resolveRefRecursive(model.modelExample, swagger);
var example = JSON.stringify(value, null, 2);
example = example.replace(/'/g, "\\'");
example = example.replace(/"/g, "'");
example = example.replace(/\n/g, "\n ");
model.modelExampleStr = example;
generate(
templates.example,
model,
path.join(modelsOutput, model.modelExampleFile + '.ts')
);
}
}
if (modelsArray.length > 0) {
modelsArray[modelsArray.length - 1].modelIsLast = true;
}
if (removeStaleFiles) {
var modelFiles = fs.readdirSync(modelsOutput);
modelFiles.forEach((file, index) => {
var ok = false;
var basename = path.basename(file);
for (var modelName in models) {
var model = models[normalizeModelName(modelName)];
if (basename == model.modelFile + '.ts'
|| basename == model.modelExampleFile + '.ts'
&& model.modelExampleStr != null) {
ok = true;
break;
}
}
if (!ok) {
rmIfExists(path.join(modelsOutput, file));
}
});
}
// Write the model index
var modelIndexFile = path.join(output, 'models.ts');
if (options.modelIndex !== false) {
generate(templates.models, { models: modelsArray }, modelIndexFile);
} else if (removeStaleFiles) {
rmIfExists(modelIndexFile);
}
// Write the StrictHttpResponse type
generate(templates.strictHttpResponse, {},
path.join(output, 'strict-http-response.ts'));
// Write the services
var servicesArray = [];
for (var serviceName in services) {
var service = services[serviceName];
service.generalErrorHandler = options.errorHandler !== false;
applyGlobals(service);
servicesArray.push(service);
generate(
templates.service,
service,
path.join(servicesOutput, service.serviceFile + '.ts')
);
}
if (servicesArray.length > 0) {
servicesArray[servicesArray.length - 1].serviceIsLast = true;
}
if (removeStaleFiles) {
var serviceFiles = fs.readdirSync(servicesOutput);
serviceFiles.forEach((file, index) => {
var ok = false;
var basename = path.basename(file);
for (var serviceName in services) {
var service = services[serviceName];
if (basename == service.serviceFile + '.ts') {
ok = true;
break;
}
}
if (!ok) {
rmIfExists(path.join(servicesOutput, file));
}
});
}
// Write the service index
var serviceIndexFile = path.join(output, 'services.ts');
if (options.serviceIndex !== false) {
generate(templates.services, { services: servicesArray }, serviceIndexFile);
} else if (removeStaleFiles) {
rmIfExists(serviceIndexFile);
}
// Write the module
var fullModuleFile = path.join(output, moduleFile + '.ts');
if (options.apiModule !== false) {
generate(templates.module, applyGlobals({
services: servicesArray
}),
fullModuleFile);
} else if (removeStaleFiles) {
rmIfExists(fullModuleFile);
}
// Write the configuration
{
var rootUrl = '';
if (swagger.hasOwnProperty('host') && swagger.host !== '') {
var schemes = swagger.schemes || [];
var scheme = schemes.length === 0 ? '//' : schemes[0] + '://';
rootUrl = scheme + swagger.host;
}
if (swagger.hasOwnProperty('basePath') && swagger.basePath !== ''
&& swagger.basePath !== '/') {
rootUrl += swagger.basePath;
}
generate(templates.configuration, applyGlobals({
rootUrl: rootUrl,
}),
path.join(output, configurationFile + '.ts')
);
}
// Write the BaseService
{
generate(templates.baseService, applyGlobals({}),
path.join(output, 'base-service.ts'));
}
}
function normalizeModelName(name) {
return name.toLowerCase();
}
/**
* Applies a filter over the given services, keeping only the specific tags.
* Also optionally removes any unused models, even services are filtered.
*/
function applyTagFilter(models, services, options) {
var i;
// Normalize the included tag names
const includeTags = options.includeTags;
var included = null;
if (includeTags && includeTags.length > 0) {
included = [];
for (i = 0; i < includeTags.length; i++) {
included.push(tagName(includeTags[i], options));
}
}
// Normalize the excluded tag names
const excludeTags = options.excludeTags;
var excluded = null;
if (excludeTags && excludeTags.length > 0) {
excluded = [];
for (i = 0; i < excludeTags.length; i++) {
excluded.push(tagName(excludeTags[i], options));
}
}
// Filter out the unused models
var ignoreUnusedModels = options.ignoreUnusedModels !== false;
var usedModels = new Set();
const addToUsed = (dep) => usedModels.add(dep);
for (var serviceName in services) {
var include =
(!included || included.indexOf(serviceName) >= 0) &&
(!excluded || excluded.indexOf(serviceName) < 0);
if (!include) {
// This service is skipped - remove it
console.info(
'Ignoring service ' + serviceName + ' because it was not included'
);
delete services[serviceName];
} else if (ignoreUnusedModels) {
// Collect the models used by this service
var service = services[serviceName];
service.serviceDependencies.forEach(addToUsed);
service.serviceErrorDependencies.forEach(addToUsed);
}
}
if (ignoreUnusedModels) {
// Collect the model dependencies of models, so unused can be removed
var allDependencies = new Set();
usedModels.forEach(dep =>
collectDependencies(allDependencies, dep, models)
);
// Remove all models that are unused
for (var modelName in models) {
var model = models[normalizeModelName(modelName)];
if (!allDependencies.has(model.modelClass)) {
// This model is not used - remove it
console.info(
'Ignoring model ' +
modelName +
' because it was not used by any service'
);
delete models[normalizeModelName(modelName)];
}
}
}
}
/**
* Collects on the given dependencies set all dependencies of the given model
*/
function collectDependencies(dependencies, model, models) {
if (!model || dependencies.has(model.modelClass)) {
return;
}
dependencies.add(model.modelClass);
if (model.modelDependencies) {
model.modelDependencies.forEach((dep) =>
collectDependencies(dependencies, dep, models)
);
}
}
/**
* Creates all sub-directories for a nested path
* Thanks to https://github.com/grj1046/node-mkdirs/blob/master/index.js
*/
function mkdirs(folderPath, mode) {
var folders = [];
var tmpPath = path.normalize(folderPath);
var exists = fs.existsSync(tmpPath);
while (!exists) {
folders.push(tmpPath);
tmpPath = path.join(tmpPath, '..');
exists = fs.existsSync(tmpPath);
}
for (var i = folders.length - 1; i >= 0; i--) {
fs.mkdirSync(folders[i], mode);
}
}
/**
* Removes the given file if it exists (logging the action)
*/
function rmIfExists(file) {
if (fs.existsSync(file)) {
console.info('Removing stale file ' + file);
fs.unlinkSync(file);
}
}
/**
* Converts a given type name into a TS file name
*/
function toFileName(typeName) {
var result = '';
var wasLower = false;
for (var i = 0; i < typeName.length; i++) {
var c = typeName.charAt(i);
var isLower = /[a-z]/.test(c);
if (!isLower && wasLower) {
result += '-';
}
result += c.toLowerCase();
wasLower = isLower;
}
return result;
}
/**
* Converts a given name into a valid class name
*/
function toClassName(name) {
var result = '';
var upNext = false;
for (var i = 0; i < name.length; i++) {
var c = name.charAt(i);
var valid = /[\w]/.test(c);
if (!valid) {
upNext = true;
} else if (upNext) {
result += c.toUpperCase();
upNext = false;
} else if (result === '') {
result = c.toUpperCase();
} else {
result += c;
}
}
if (/[0-9]/.test(result.charAt(0))) {
result = '_' + result;
}
return result;
}
/**
* Resolves the simple reference name from a qualified reference
*/
function simpleRef(ref) {
if (!ref) {
return null;
}
var index = ref.lastIndexOf('/');
if (index >= 0) {
ref = ref.substr(index + 1);
}
return toClassName(ref);
}
/**
* Converts a given enum value into the enum name
*/
function toEnumName(value) {
var result = '';
var wasLower = false;
for (var i = 0; i < value.length; i++) {
var c = value.charAt(i);
var isLower = /[a-z]/.test(c);
if (!isLower && wasLower) {
result += '_';
}
result += c.toUpperCase();
wasLower = isLower;
}
if (!isNaN(value[0])) {
result = '_' + result;
}
result = result.replace(/[^\w]/g, '_');
result = result.replace(/_+/g, '_');
return result;
}
/**
* Returns a multi-line comment for the given text
*/
function toComments(text, level) {
var indent = '';
var i;
for (i = 0; i < level; i++) {
indent += ' ';
}
if (text == null || text.length === 0) {
return indent;
}
const lines = text.trim().split('\n');
var result = '\n' + indent + '/**\n';
lines.forEach(line => {
result += indent + ' *' + (line === '' ? '' : ' ' + line) + '\n';
});
result += indent + ' */\n' + indent;
return result;
}
/**
* Class used to resolve the model dependencies
*/
function DependenciesResolver(models, ownType) {
this.models = models;
this.ownType = ownType;
this.dependencies = [];
this.dependencyNames = [];
}
/**
* Adds a candidate dependency
*/
DependenciesResolver.prototype.add = function (input) {
let deps;
if (input.allTypes) {
deps = input.allTypes;
} else {
deps = [removeBrackets(input)];
}
for (let i = 0; i < deps.length; i++) {
let dep = deps[i];
if (this.dependencyNames.indexOf(dep) < 0 && dep !== this.ownType) {
var depModel = this.models[normalizeModelName(dep)];
if (depModel) {
this.dependencies.push(depModel);
this.dependencyNames.push(depModel.modelClass);
}
}
}
};
/**
* Returns the resolved dependencies as a list of models
*/
DependenciesResolver.prototype.get = function () {
return this.dependencies;
};
/**
* Process each model, returning an object keyed by model name, whose values
* are simplified descriptors for models.
*/
function processModels(swagger, options) {
var name, model, i, property;
var models = {};
for (name in swagger.definitions) {
model = swagger.definitions[name];
var parents = null;
var properties = null;
var requiredProperties = null;
var additionalPropertiesType = false;
var example = model.example || null;
var enumValues = null;
var elementType = null;
var simpleType = null;
if (model.allOf != null && model.allOf.length > 0) {
parents = model.allOf
.filter(parent => !!parent.$ref)
.map(parent => simpleRef(parent.$ref));
properties = (model.allOf.find(val => !!val.properties) || {}).properties || {};
requiredProperties = (model.allOf.find(val => !!val.required) || {}).required || [];
if (parents && parents.length) {
simpleType = null;
enumValues = null;
}
} else if (model.type === 'string') {
enumValues = model.enum || [];
if (enumValues.length == 0) {
simpleType = 'string';
enumValues = null;
} else {
for (i = 0; i < enumValues.length; i++) {
var enumValue = enumValues[i];
var enumDescriptor = {
enumName: toEnumName(enumValue),
enumValue: String(enumValue).replace(/\'/g, '\\\''),
enumIsLast: i === enumValues.length - 1,
};
enumValues[i] = enumDescriptor;
}
}
} else if (model.type === 'array') {
elementType = propertyType(model);
} else if (!model.type && (model.anyOf || model.oneOf)) {
let of = model.anyOf || model.oneOf;
let variants = of.map(propertyType);
simpleType = {
allTypes: mergeTypes(...variants),
toString: () => variants.join(' |\n ')
};
} else if (model.type === 'object' || model.type === undefined) {
properties = model.properties || {};
requiredProperties = model.required || [];
additionalPropertiesType = model.additionalProperties &&
(typeof model.additionalProperties === 'object' ? propertyType(model.additionalProperties) : 'any');
} else {
simpleType = propertyType(model);
}
var modelClass = toClassName(name);
var descriptor = {
modelName: name,
modelClass: modelClass,
modelFile: toFileName(modelClass) + options.customFileSuffix.model,
modelComments: toComments(model.description),
modelParents: parents,
modelIsObject: properties != null,
modelIsEnum: enumValues != null,
modelIsArray: elementType != null,
modelIsSimple: simpleType != null,
modelSimpleType: simpleType,
properties: properties == null ? null :
processProperties(swagger, properties, requiredProperties),
modelExample: example,
modelAdditionalPropertiesType: additionalPropertiesType,
modelExampleFile: toFileName(name) + options.customFileSuffix.example,
modelEnumValues: enumValues,
modelElementType: elementType,
modelSubclasses: [],
};
if (descriptor.properties != null) {
descriptor.modelProperties = [];
for (var propertyName in descriptor.properties) {
property = descriptor.properties[propertyName];
descriptor.modelProperties.push(property);
}
descriptor.modelProperties.sort((a, b) => {
return a.propertyName < b.propertyName ? -1 :
a.propertyName > b.propertyName ? 1 : 0;
});
if (descriptor.modelProperties.length > 0) {
descriptor.modelProperties[
descriptor.modelProperties.length - 1
].propertyIsLast = true;
}
}
models[normalizeModelName(name)] = descriptor;
models[normalizeModelName(descriptor.modelClass)] = descriptor;
}
// Now that we know all models, process the hierarchies
for (name in models) {
model = models[normalizeModelName(name)];
if (!model.modelIsObject) {
// Only objects can have hierarchies
continue;
}
// Process the hierarchy
var parents = model.modelParents;
if (parents && parents.length > 0) {
model.modelParents = parents
.filter(parentName => !!parentName)
.map(parentName => {
// Make the parent be the actual model, not the name
var parentModel = models[normalizeModelName(parentName)];
// Append this model on the parent's subclasses
parentModel.modelSubclasses.push(model);
return parentModel;
});
model.modelParentNames = model.modelParents.map(
(parent, index) => ({
modelClass: parent.modelClass,
parentIsFirst: index === 0,
})
);
}
}
// Now that the model hierarchy is ok, resolve the dependencies
var addToDependencies = t => {
if (Array.isArray(t.allTypes)) {
t.allTypes.forEach(it => dependencies.add(it));
}
else dependencies.add(t);
};
for (name in models) {
model = models[normalizeModelName(name)];
if (model.modelIsEnum || model.modelIsSimple && !model.modelSimpleType.allTypes) {
// Enums or simple types have no dependencies
continue;
}
var dependencies = new DependenciesResolver(models, model.modelName);
// The parent is a dependency
if (model.modelParents) {
model.modelParents.forEach(modelParent => {
dependencies.add(modelParent.modelName);
})
}
// Each property may add a dependency
if (model.modelProperties) {
for (i = 0; i < model.modelProperties.length; i++) {
property = model.modelProperties[i];
addToDependencies(property.propertyType);
}
}
// If an array, the element type is a dependency
if (model.modelElementType) addToDependencies(model.modelElementType);
if (model.modelSimpleType) addToDependencies(model.modelSimpleType);
if (model.modelAdditionalPropertiesType) addToDependencies(model.modelAdditionalPropertiesType);
model.modelDependencies = dependencies.get();
}
return models;
}
/**
* Removes an array designation from the given type.
* For example, "Array<a>" returns "a", "a[]" returns "a", while "b" returns "b".
* A special case is for inline objects. In this case, the result is "object".
*/
function removeBrackets(type, nullOrUndefinedOnly) {
if (typeof nullOrUndefinedOnly === "undefined") {
nullOrUndefinedOnly = false;
}
if (typeof type === 'object') {
if (type.allTypes && type.allTypes.length === 1) {
return removeBrackets(type.allTypes[0], nullOrUndefinedOnly);
}
return 'object';
}
else if (type.replace(/ /g, '') !== type) {
return removeBrackets(type.replace(/ /g, ''));
}
else if (type.indexOf('null|') === 0) {
return removeBrackets(type.substr('null|'.length));
}
else if (type.indexOf('undefined|') === 0) {
// Not used currently, but robust code is better code :)
return removeBrackets(type.substr('undefined|'.length));
}
if (type == null || type.length === 0 || nullOrUndefinedOnly) {
return type;
}
var pos = type.indexOf('Array<');
if (pos >= 0) {
var start = 'Array<'.length;
return type.substr(start, type.length - start - 1);
}
pos = type.indexOf('[');
return pos >= 0 ? type.substr(0, pos) : type;
}
/**
* Combine dependencies of multiple types.
* @param types
* @return {Array}
*/
function mergeTypes(...types) {
let allTypes = [];
types.forEach(type => {
(type.allTypes || [type]).forEach(type => {
if (allTypes.indexOf(type) < 0) allTypes.push(type);
});
});
return allTypes;
}
/**
* Returns the TypeScript property type for the given raw property
*/
function propertyType(property) {
var type;
if (property === null || property.type === null) {
return 'null';
} else if (property.$ref != null) {
// Type is a reference
return simpleRef(property.$ref);
} else if (property['x-type']) {
// Type is read from the x-type vendor extension
type = (property['x-type'] || '').toString().replace('List<', 'Array<');
return type.length == 0 ? 'null' : type;
} else if (property['x-nullable']) {
return 'null | ' + propertyType(
Object.assign(property, { 'x-nullable': undefined }));
} else if (!property.type && (property.anyOf || property.oneOf)) {
let variants = (property.anyOf || property.oneOf).map(propertyType);
return {
allTypes: mergeTypes(...variants),
toString: () => variants.join(' | ')
};
} else if (!property.type && property.allOf) {
// Do not want to include x-nullable types as part of an allOf union.
let variants = (property.allOf).filter(prop => !prop['x-nullable']).map(propertyType);
return {
allTypes: mergeTypes(...variants),
toString: () => variants.join(' & ')
};
} else if (Array.isArray(property.type)) {
let variants = property.type.map(type => propertyType(Object.assign({}, property, { type })));
return {
allTypes: mergeTypes(...variants),
toString: () => variants.join(' | ')
};
}
switch (property.type) {
case 'null':
return 'null';
case 'string':
if (property.enum && property.enum.length > 0) {
return '\'' + property.enum.join('\' | \'') + '\'';
}
else if (property.const) {
return '\'' + property.const + '\'';
}
else if (property.format === 'byte') {
return 'ArrayBuffer';
}
return 'string';
case 'array':
if (Array.isArray(property.items)) { // support for tuples
if (!property.maxItems) return 'Array<any>'; // there is unable to define unlimited tuple in TypeScript
let minItems = property.minItems || 0,
maxItems = property.maxItems,
types = property.items.map(propertyType);
types.push(property.additionalItems ? propertyType(property.additionalItems) : 'any');
let variants = [];
for (let i = minItems; i <= maxItems; i++) variants.push(types.slice(0, i));
return {
allTypes: mergeTypes(...types.slice(0, maxItems)),
toString: () => variants.map(types => `[${types.join(', ')}]`).join(' | ')
};
}
else {
let itemType = propertyType(property.items);
return {
allTypes: mergeTypes(itemType),
toString: () => 'Array<' + itemType + '>'
};
}
case 'integer':
case 'number':
if (property.enum && property.enum.length > 0) return property.enum.join(' | ');
if (property.const) return property.const;
return 'number';
case 'boolean':
return 'boolean';
case 'file':
return 'Blob';
case 'object':
var def = '{';
let memberCount = 0;
var allTypes = [];
if (property.properties) {
for (var name in property.properties) {
var prop = property.properties[name];
if (memberCount++) def += ', ';
type = propertyType(prop);
allTypes.push(type);
let required = property.required && property.required.indexOf(name) >= 0;
def += name + (required ? ': ' : '?: ') + type;
}
}
if (property.additionalProperties) {
if (memberCount++) def += ', ';
type = typeof property.additionalProperties === 'object' ?
propertyType(property.additionalProperties) : 'any';
allTypes.push(type);
def += '[key: string]: ' + type;
}
def += '}';
return {
allTypes: mergeTypes(...allTypes),
toString: () => def,
};
default:
return 'any';
}
}
/**
* Process each property for the given properties object, returning an object
* keyed by property name with simplified property types
*/
function processProperties(swagger, properties, requiredProperties) {
var result = {};
for (var name in properties) {
var property = properties[name];
var descriptor = {
propertyName: name.indexOf('-') === -1 && name.indexOf(".") === -1 ? name : `"${name}"`,
propertyComments: toComments(property.description, 1),
propertyRequired: requiredProperties.indexOf(name) >= 0,
propertyType: propertyType(property),
};
result[name] = descriptor;
}
return result;
}
/**
* Resolves a local reference in the given swagger file
*/
function resolveRef(swagger, ref) {
if (ref.indexOf('#/') != 0) {
console.error('Resolved references must start with #/. Current: ' + ref);
process.exit(1);
}
var parts = ref.substr(2).split('/');
var result = swagger;
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
result = result[part];
}
return result === swagger ? {} : result;
}
/*
* Process an operation's possible responses. Returns an object keyed
* by each HTTP code, whose values are objects with code and type properties,
* plus a property resultType, which is the type to the HTTP 2xx code.
*/
function processResponses(swagger, def, path, models) {
var responses = def.responses || {};
var operationResponses = {};
operationResponses.returnHeaders = false;
for (var code in responses) {