-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
1668 lines (1640 loc) · 70.3 KB
/
index.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
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 96,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function (local) {
'use strict';
// run shared js-env code
(function () {
local.swmg.normalizeIdMongodb = function (data) {
/*
* this function will recursively convert the property id to _id
*/
local.utility2.objectTraverse(data, function (element) {
if (element && element.id) {
element._id = element._id || element.id;
delete element.id;
}
});
return data;
};
local.swmg.normalizeIdSwagger = function (data) {
/*
* this function will recursively convert the property _id to id
*/
local.utility2.objectTraverse(data, function (element) {
if (element && element._id) {
element.id = element.id || element._id;
delete element._id;
}
});
return data;
};
local.swmg.normalizeParamDictSwagger = function (data, methodPath) {
/*
* this function will parse the data according to methodPath.parameters
*/
var tmp;
methodPath.parameters.forEach(function (paramDef) {
tmp = data[paramDef.name];
// init default value
if (tmp === undefined) {
// jsonCopy object to prevent side-effects
data[paramDef.name] = local.utility2.jsonCopy(paramDef.default);
}
// parse csv array
if (paramDef.type === 'array' &&
paramDef.collectionFormat &&
typeof tmp === 'string') {
switch (paramDef.collectionFormat) {
case 'csv':
tmp = tmp.split(',');
break;
case 'pipes':
tmp = tmp.split('|');
break;
case 'ssv':
tmp = tmp.split(' ');
break;
case 'tsv':
tmp = tmp.split('\t');
break;
}
}
// JSON.parse swmgParamDict
if (paramDef.type !== 'string' &&
(typeof tmp === 'string' ||
(local.modeJs === 'node' && Buffer.isBuffer(tmp)))) {
try {
tmp = JSON.parse(tmp);
} catch (ignore) {
}
}
data[paramDef.name] = tmp;
});
return data;
};
local.swmg.onErrorJsonapi = function (options, onError) {
/*
* this function will convert the error and data to jsonapi format,
* http://jsonapi.org/format/#errors
* and pass them to onError
*/
return function (error, data) {
if (typeof options === 'function') {
options = options();
}
options = options || {};
options.id = options.id || local.utility2.uuidTime();
// handle error
if (error) {
if (error.errors && Array.isArray(error.errors) && error.errors[0]) {
onError(error);
return;
}
// prepend mongodb-errmsg
if (error.errmsg) {
local.utility2.errorMessagePrepend(error, error.errmsg + '\n');
}
options.message = error.message;
options.stack = error.stack;
options.statusCode = Number(error.statusCode) || 500;
options.errors = local.utility2
.jsonCopy(local.swmg.normalizeIdSwagger(error));
local.utility2.objectSetDefault(options.errors, {
code: options.statusCode,
detail: options.stack,
id: options.id,
message: options.message
});
options.errors.code = String(options.errors.code);
options.errors.detail = String(options.errors.detail);
options.errors.id = String(options.errors.id);
options.errors.message = String(options.errors.message);
options.errors = [options.errors];
onError(options);
return;
}
// handle data
options.data = data;
local.swmg.normalizeIdSwagger(options);
if (!Array.isArray(options.data)) {
options.data = [options.data];
}
onError(null, options);
};
};
local.swmg.schemaDereference = function ($ref) {
/*
* this function will try to dereference the schema from $ref
*/
try {
return ((local.global.swaggerUi &&
local.global.swaggerUi.api &&
local.global.swaggerUi.api.swaggerJson) ||
local.swmg.swaggerJson)
.definitions[(/^\#\/definitions\/(\w+)$/).exec($ref)[1]];
} catch (ignore) {
}
};
local.swmg.validateByParamDefList = function (options) {
/*
* this function will validate options.data against options.paramDefList
*/
var data, key;
try {
data = options.data;
// validate data
local.utility2.assert(data && typeof data === 'object', data);
(options.paramDefList || []).forEach(function (paramDef) {
key = paramDef.name;
local.swmg.validateByPropertyDef({
data: data[key],
key: key,
propertyDef: paramDef,
required: paramDef.required
});
});
} catch (errorCaught) {
local.utility2.errorMessagePrepend(errorCaught, '"' + options.key + '.' + key +
'" - ');
throw errorCaught;
}
};
local.swmg.validateByPropertyDef = function (options) {
/*
* this function will validate options.data against options.propertyDef
*/
var assert, data, propertyDef, tmp;
assert = function (valid) {
if (!valid) {
throw new Error('invalid "' + options.key + ':' + (propertyDef.format ||
propertyDef.type) + '" property - ' + JSON.stringify(data));
}
};
data = options.data;
propertyDef = options.propertyDef;
// validate undefined data
if (data === null || data === undefined) {
if (options.required) {
throw new Error('required "' + options.key + ':' + (propertyDef.format ||
propertyDef.type) + '" property cannot be null or undefined');
}
return;
}
// validate schema
tmp = propertyDef.$ref || (propertyDef.schema && propertyDef.schema.$ref);
if (tmp) {
local.swmg.validateBySchema({
circularList: options.circularList,
data: data,
key: tmp,
schema: local.swmg.schemaDereference(tmp)
});
return;
}
// init circularList
if (data && typeof data === 'object') {
options.circularList = options.circularList || [];
if (options.circularList.indexOf(data) >= 0) {
return;
}
options.circularList.push(data);
}
// validate propertyDef embedded in propertyDef.schema.type
if (!propertyDef.type && propertyDef.schema && propertyDef.schema.type) {
propertyDef = propertyDef.schema;
}
// validate propertyDef.type
// https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md
// #data-types
switch (propertyDef.type) {
case 'array':
assert(Array.isArray(data) && propertyDef.items);
// recurse - validate elements in list
data.forEach(function (element) {
local.swmg.validateByPropertyDef({
circularList: options.circularList,
data: element,
key: options.key,
propertyDef: propertyDef.items
});
});
break;
case 'boolean':
assert(typeof data === 'boolean');
break;
case 'integer':
assert(typeof data === 'number' && isFinite(data) && (data | 0) === data);
switch (propertyDef.format) {
case 'int32':
case 'int64':
break;
}
break;
case 'number':
assert(typeof data === 'number' && isFinite(data));
switch (propertyDef.format) {
case 'double':
case 'float':
break;
}
break;
case 'object':
assert(typeof data === 'object');
break;
case 'string':
assert(typeof data === 'string');
switch (propertyDef.format) {
// https://github.com/swagger-api/swagger-spec/issues/50
case 'byte':
assert(!(/[^\n\r\+\/0-9\=A-Za-z]/).test(data));
break;
case 'date':
tmp = new Date(data);
assert(tmp.getTime() && data === tmp.toISOString().slice(0, 10));
break;
case 'date-time':
tmp = new Date(data);
assert(tmp.getTime() &&
data.slice(0, 19) === tmp.toISOString().slice(0, 19));
break;
case 'email':
assert(local.utility2.regexpEmailValidate.test(data));
break;
case 'json':
try {
JSON.parse(data);
} catch (errorCaught) {
assert(null);
}
break;
}
break;
}
};
local.swmg.validateBySchema = function (options) {
/*
* this function will validate options.data against options.schema
*/
var data, key, schema;
try {
data = options.data;
// init circularList
if (data && typeof data === 'object') {
options.circularList = options.circularList || [];
if (options.circularList.indexOf(data) >= 0) {
return;
}
options.circularList.push(data);
}
// validate data
switch (options.key) {
// ignore undefined schema
case '#/definitions/Undefined':
return;
}
local.utility2.assert(data && typeof data === 'object', 'invalid data ' + data);
schema = options.schema;
// validate schema
local.utility2.assert(
schema && typeof schema === 'object',
'invalid schema ' + schema
);
Object.keys(schema.properties || {}).forEach(function (_) {
key = _;
local.swmg.validateByPropertyDef({
circularList: options.circularList,
data: data[key],
depth: options.depth - 1,
key: key,
propertyDef: schema.properties[key],
required: schema.required && schema.required.indexOf(key) >= 0
});
});
} catch (errorCaught) {
local.utility2.errorMessagePrepend(errorCaught, '"' + options.key + '.' + key +
'" - ');
throw errorCaught;
}
};
local.swmg.validateBySwagger = function (options) {
/*
* this function will validate the entire swagger json object
*/
local.swagger_tools.v2.validate(
// jsonCopy object to prevent side-effects
local.utility2.jsonCopy(options),
function (error, result) {
// validate no error occurred
local.utility2.assert(!error, error);
['errors', 'undefined', 'warnings'].forEach(function (errorType) {
((result && result[errorType]) || [
]).slice(0, 8).forEach(function (element) {
console.error('swagger schema - ' + errorType.slice(0, -1) + ' - ' +
element.code + ' - ' + element.message + ' - ' +
JSON.stringify(element.path));
});
});
error = result && result.errors && result.errors[0];
// validate no error occurred
local.utility2.assert(!error, new Error(error && error.message));
}
);
};
}());
switch (local.modeJs) {
// run node js-env code
case 'node':
local.swmg._crudApi = function (options, onError) {
/*
* this function will run the low-level crud-api on the given options.data
*/
var modeNext, onNext;
options.onError2 = local.swmg.onErrorJsonapi(function () {
return options.response;
}, onError);
modeNext = 0;
onNext = local.utility2.onErrorWithStack(function (error, data) {
local.utility2.testTryCatch(function () {
modeNext = error
? Infinity
: modeNext + 1;
switch (modeNext) {
case 1:
// jsonCopy object to prevent side-effects
options.data = local.utility2.jsonCopy(options.data);
// validate params
local.swmg.validateByParamDefList({
data: options.data,
key: options.schemaName + '.' + options.operationId,
paramDefList: options.paramDefList
});
// convert id to mongodb format
local.swmg.normalizeIdMongodb(options);
// init body
options.data.body = options.data.body || {};
// init id
options.data._id = options.data.body._id =
String(options.data.body._id ||
options.data._id ||
local.utility2.uuidTime());
options.optionsId = options.optionsId || { _id: options.data._id };
options.optionsIdKey = Object.keys(options.optionsId)[0];
// init collection
options.collection =
local.swmg.cacheDict.collection[options.collectionName];
// init response
options.response = { _id: options.data._id };
// init _timeCreated
switch (options.operationId) {
case 'crudUpdateOne':
options.collection
.findOne(options.optionsId, { _timeCreated: 1 }, onNext);
return;
}
onNext();
break;
case 2:
// init _timeCreated and _timeModified
options.tmp = data && data._timeCreated;
switch (options.operationId) {
case 'crudCreateOne':
case 'crudReplaceOne':
options.data.body._timeCreated =
options.data.body._timeModified = new Date().toISOString();
break;
case 'crudUpdateOne':
options.data.body._timeCreated =
options.data.body._timeModified = new Date().toISOString();
if (options.tmp < options.data.body._timeCreated &&
new Date(options.tmp).getTime()) {
options.data.body._timeCreated = options.tmp;
}
break;
}
switch (options.operationId) {
case 'crudAggregateMany':
// aggregate data
options.collection.aggregate(local.swmg
.normalizeIdMongodb(options.data.body), onNext);
break;
case 'crudCountByQueryOne':
// count data
options.collection.count(local.swmg
.normalizeIdMongodb(JSON.parse(options.data.query)), onNext);
break;
case 'crudCreateOne':
// insert data
options.collection.insert(options.data.body, onNext);
break;
case 'crudDeleteByIdOne':
// delete data
options.collection.removeOne(options.optionsId, onNext);
break;
case 'crudDeleteByQueryMany':
// delete data
options.collection.remove(local.swmg
.normalizeIdMongodb(JSON.parse(options.data.query)), onNext);
break;
case 'crudExistsByIdOne':
// find data
options.collection.findOne(options.optionsId, { _id: 1 }, onNext);
break;
case 'crudGetByIdOne':
// find data
options.collection.findOne(options.optionsId, onNext);
break;
case 'crudGetByQueryMany':
data = local.swmg.normalizeIdMongodb([
JSON.parse(options.data.query),
JSON.parse(options.data.fields),
{
hint: JSON.parse(options.data.hint),
limit: options.data.limit,
skip: options.data.skip,
sort: JSON.parse(options.data.sort)
}
]);
// find data
options.cursor = options.collection.find(data[0], data[1], data[2]);
options.cursor.toArray(onNext);
break;
case 'crudGetDistinctValueByPropertyMany':
// find data
options.collection.distinct(
options.data.field.replace((/^id$/), '_id'),
local.swmg.normalizeIdMongodb(JSON.parse(options.data.query)),
onNext
);
break;
case 'crudCreateMany':
case 'crudReplaceMany':
// insert / replace data
if (!options.data.body.length) {
options.response.data = [];
modeNext = Infinity;
onNext();
break;
}
options.bulk = options.collection.initializeOrderedBulkOp();
options.data.body.forEach(function (element) {
// init id
element._id = element._id || local.utility2.uuidTime();
element[options.optionsIdKey] = element[options.optionsIdKey] ||
element._id;
// init _timeCreated and _timeModified
element._timeCreated =
element._timeModified = new Date().toISOString();
switch (options.operationId) {
case 'crudCreateMany':
// insert data
options.bulk.insert(element);
break;
case 'crudReplaceMany':
options.bulkFindQuery = {};
options.bulkFindQuery[options.optionsIdKey] =
element[options.optionsIdKey];
options.bulkFind = options.bulk.find(options.bulkFindQuery);
// upsert data
if (options.data.upsert) {
options.bulkFind = options.bulkFind.upsert();
}
// replace data
options.bulkFind.replaceOne(element);
break;
}
});
options.bulk.execute(onNext);
break;
case 'crudReplaceOne':
// replace data
options.collection.update(options.optionsId, options.data.body, {
upsert: options.data.upsert
}, onNext);
break;
case 'crudUpdateOne':
// update data
options.collection.update(options
.optionsId, { $set: options.data.body }, {
upsert: options.data.upsert
}, onNext);
break;
default:
onNext(new Error('undefined crud operation - ' +
options.schemaName + '.' + options.operationId));
}
break;
case 3:
// jsonCopy object to prevent side-effects
data = local.utility2.jsonCopy(data);
switch (options.operationId) {
case 'crudAggregateMany':
case 'crudCountByQueryOne':
case 'crudGetByIdOne':
case 'crudGetDistinctValueByPropertyMany':
case 'crudGetByQueryMany':
options.response.data = data;
break;
case 'crudCreateMany':
case 'crudReplaceMany':
options.response.meta = data;
options.collection.find({
_id: { $in: options.data.body.map(function (element) {
return element._id;
}) }
}).toArray(onNext);
return;
case 'crudCreateOne':
case 'crudReplaceOne':
case 'crudUpdateOne':
options.response.meta = data;
if ((data.n || (data.result && data.result.n)) !== 1) {
onNext(new Error(options.operationId + ' failed'));
return;
}
options.collection.findOne(options.optionsId, onNext);
return;
case 'crudDeleteByIdOne':
case 'crudDeleteByQueryMany':
options.response.meta = data;
break;
case 'crudExistsByIdOne':
options.response.data = !!data;
break;
}
modeNext += 1;
onNext(error);
break;
case 4:
switch (options.operationId) {
case 'crudCreateMany':
case 'crudReplaceMany':
options.tmp = {};
data.forEach(function (element) {
options.tmp[element._id] = element;
});
options.response.data = options.data.body.map(function (element) {
return options.tmp[element._id];
});
break;
default:
// jsonCopy object to prevent side-effects
options.response.data = local.utility2.jsonCopy(data);
}
onNext();
break;
default:
options.onError2(error, options.response.data);
}
}, options.onError2);
});
onNext();
};
local.swmg.apiUpdate = function (options) {
/*
* this function will update the api
*/
var methodPath, tmp;
options.definitions = options.definitions || {};
options.paths = options.paths || {};
Object.keys(options.definitions).forEach(function (schemaName) {
var schema;
schema = options.definitions[schemaName];
schema._schemaName = schemaName;
if (!schema._collectionName) {
return;
}
local.utility2.objectSetDefault(options, JSON.parse(JSON.stringify({
definitions: {
// init JsonapiResponse{{_schemaName}}
'JsonapiResponse{{_schemaName}}': {
properties: { data: {
items: { $ref: '#/definitions/{{_schemaName}}' },
type: 'array'
} },
'x-inheritList': [{ $ref: '#/definitions/JsonapiResponse' }]
}
}
}).replace((/\{\{_schemaName\}\}/g), schemaName)), 2);
// hack - init swaggerJson$$Dummy,
// to pass validation warnings for auto-created schemas
tmp = local.swmg.swaggerJson$$Dummy;
local.utility2.objectSetOverride(tmp, JSON.parse(JSON.stringify({
paths: { '/$$Dummy/{{_schemaName}}': { get: {
responses: {
200: {
description: '',
schema: { $ref:
'#/definitions/JsonapiResponse{{_schemaName}}' }
}
}
} } }
}).replace((/\{\{_schemaName\}\}/g), schemaName)), 2);
// init crud-api
(schema._crudApiList || []).forEach(function (methodPath) {
methodPath = JSON.parse(local.swmg.cacheDict.methodPathCrudDefault[
methodPath
]
.replace((/\{\{_collectionName\}\}/g), schema._collectionName)
.replace((/\{\{_crudApi\}\}/g), schema._crudApi)
.replace((/\{\{_schemaName\}\}/g), schema._schemaName));
options.paths[methodPath._path] = options.paths[methodPath._path] || {};
options.paths[methodPath._path][methodPath._method] = methodPath;
});
// init collectionName / crudApi / schemaName
schema = options.definitions[schemaName] = JSON.parse(
JSON.stringify(schema)
.replace((/\{\{_collectionName\}\}/g), schema._collectionName)
.replace((/\{\{_crudApi\}\}/g), schema._crudApi)
.replace((/\{\{_schemaName\}\}/g), schema._schemaName)
);
// update cacheDict.collection
local.utility2.onReady.counter += 1;
local.utility2.taskRunOrSubscribe({
key: 'swagger-mongodb.mongodbConnect'
}, function () {
local.swmg.collectionCreate(schema, local.utility2.onReady);
});
});
// update paths
Object.keys(options.paths).forEach(function (path) {
Object.keys(options.paths[path]).forEach(function (method) {
methodPath = options.paths[path][method];
methodPath._method = method;
methodPath._path = path;
// init crud-api
tmp = methodPath._crudApi &&
local.swmg.cacheDict.methodPathCrudDefault[methodPath.operationId];
if (tmp) {
local.utility2.objectSetDefault(methodPath, JSON.parse(tmp), 2);
}
// init methodPath
local.utility2.objectSetDefault(methodPath, {
parameters: [],
responses: {
200: {
description: 'ok - ' +
'http://jsonapi.org/format/#document-top-level',
schema: { $ref: '#/definitions/JsonapiResponse' }
}
},
tags: []
}, 2);
// init collectionName / crudApi / schemaName
local.utility2.objectSetOverride(methodPath, JSON.parse(
JSON.stringify(methodPath)
.replace((/\{\{_collectionName\}\}/g), methodPath._collectionName)
.replace((/\{\{_crudApi\}\}/g), methodPath._crudApi)
.replace((/\{\{_schemaName\}\}/g), methodPath._schemaName)
), 1);
// update cacheDict.methodPath
local.swmg.cacheDict.methodPath[method.toUpperCase() + ' ' + path.replace(
(/\{.*/),
function (match0) {
return match0.replace((/[^\/]/g), '');
}
)] = JSON.stringify(methodPath);
});
});
// merge tags
tmp = {};
// update tags from options._tagDict
Object.keys(options._tagDict || {}).forEach(function (key) {
tmp[key] = options._tagDict[key];
tmp[key].name = key;
});
// update tags from options.tags
[local.swmg.swaggerJson.tags, options.tags].forEach(function (tags) {
(tags || []).forEach(function (element) {
tmp[element.name] = element;
});
});
tmp = local.swmg.swaggerJson.tags = Object.keys(tmp).sort().map(function (key) {
return tmp[key];
});
// update swaggerJson with options, with underscore keys removed
local.utility2.objectSetOverride(
local.swmg.swaggerJson,
local.utility2.objectTraverse(
// jsonCopy object to prevent side-effects
local.utility2.jsonCopy(options),
function (element) {
if (element && typeof element === 'object') {
Object.keys(element).forEach(function (key) {
// security - remove underscore key
if (key[0] === '_') {
delete element[key];
}
});
}
}
),
2
);
// restore tags
local.swmg.swaggerJson.tags = tmp;
// init properties from x-inheritList
[0, 1, 2, 3].forEach(function () {
Object.keys(local.swmg.swaggerJson.definitions).forEach(function (schema) {
schema = local.swmg.swaggerJson.definitions[schema];
// jsonCopy object to prevent side-effects
local.utility2.jsonCopy(schema['x-inheritList'] || [])
.reverse()
.forEach(function (element) {
local.utility2.objectSetDefault(schema, {
properties:
local.swmg.schemaDereference(element.$ref).properties
}, 2);
});
});
});
// jsonCopy object to prevent side-effects
local.swmg.swaggerJson = JSON.parse(local.utility2
.jsonStringifyOrdered(local.utility2.jsonCopy(local.swmg.swaggerJson)));
// validate swaggerJson
local.swmg.validateBySwagger(local.utility2.objectSetDefault(
local.utility2.jsonCopy(local.swmg.swaggerJson),
local.swmg.swaggerJson$$Dummy,
2
));
// init crud-api
local.swmg.api = new local.swmg.SwaggerClient({
url: 'http://localhost:' + local.utility2.serverPortInit()
});
local.swmg.api.buildFromSpec(local.utility2.jsonCopy(local.swmg.swaggerJson));
};
local.swmg.collectionCreate = function (schema, onError) {
/*
* this function will create a mongodb collection
*/
var collection, modeNext, onNext;
modeNext = 0;
onNext = function (error) {
// validate no error occurred
local.utility2.assert(!error, error);
modeNext += 1;
switch (modeNext) {
case 1:
collection = local.swmg.cacheDict.collection[schema._collectionName] =
local.swmg.db.collection(schema._collectionName);
// if $npm_config_mode_mongodb_readonly, then return this function
if (local.utility2.envDict.npm_config_mode_mongodb_readonly ||
schema._collectionReadonly) {
onError();
return;
}
// drop collection on init
if (schema._collectionDrop) {
console.warn('dropping collection ' + schema._collectionName + ' ...');
local.swmg.db.command({ drop: schema._collectionName }, function () {
onNext();
});
return;
}
onNext();
return;
case 2:
// create collection
if (schema._collectionCreate) {
local.swmg.db.createCollection(
schema._collectionName,
schema._collectionCreate,
function () {
// convert existing collection to capped collection
collection.isCapped(function (error, data) {
if (!error && !data && schema._collectionCreate.capped) {
local.swmg.db.command({
convertToCapped: schema._collectionName,
size: schema._collectionCreate.size
}, onNext);
return;
}
onNext();
});
}
);
return;
}
onNext();
return;
case 3:
// create index
if (schema._collectionCreateIndexList) {
local.swmg.db.command({
createIndexes: schema._collectionName,
indexes: schema._collectionCreateIndexList
}, onNext);
return;
}
onNext();
return;
case 4:
// upsert fixtures
local.swmg._crudApi({
collectionName: schema._collectionName,
data: {
body: local.utility2.jsonCopy(schema._collectionFixtureList || []),
upsert: true
},
operationId: 'crudReplaceMany',
schemaName: schema._schemaName
}, onNext);
return;
default:
onError();
}
};
onNext();
};
local.swmg.middlewareBodyParse = function (request, response, nextMiddleware) {
/*
* this function will parse the request-body
*/
// jslint-hack
local.utility2.nop(response);
local.utility2.testTryCatch(function () {
if (request.swmgBodyParsed) {
nextMiddleware();
return;
}
request.swmgBodyParsed = String(request.bodyRaw);
switch ((/[^;]*/).exec(request.headers['content-type'] || '')[0]) {
case 'application/x-www-form-urlencoded':
request.swmgBodyParsed =
local.url.parse('?' + request.swmgBodyParsed, true).query;
break;
default:
try {
request.swmgBodyParsed = JSON.parse(request.swmgBodyParsed);
} catch (ignore) {
}
}
nextMiddleware();
}, nextMiddleware);
};
local.swmg.middlewareError = function (error, request, response) {
/*
* this function will handle errors according to http://jsonapi.org/format/#errors
*/
if (!error) {
error = new Error('404 Not Found');
error.statusCode = 404;
}
local.swmg.onErrorJsonapi(null, function (error) {
local.utility2.serverRespondHeadSet(request, response, error.statusCode, {});
// debug statusCode / method / url
local.utility2.errorMessagePrepend(error, response.statusCode + ' ' +
request.method + ' ' + request.url + '\n');
// print error.stack to stderr
local.utility2.onErrorDefault(error);
response.end(JSON.stringify(error));
})(error);
};
local.swmg.middlewareSwagger = function (request, response, nextMiddleware) {
/*
* this function will run the main swagger-mongodb middleware
*/
var modeNext, onNext, tmp;
modeNext = 0;
onNext = function (error) {
local.utility2.testTryCatch(function () {
modeNext = error
? Infinity
: modeNext + 1;
switch (modeNext) {
case 1:
// if request.url is not prefixed with swaggerJson.basePath,
// then default to nextMiddleware
if (request.urlParsed.pathnameNormalized
.indexOf(local.swmg.swaggerJson.basePath) !== 0) {
modeNext = Infinity;
onNext();
return;
}
// init swmgPathname
request.swmgPathname = request.method + ' ' +
request.urlParsed.pathnameNormalized
.replace(local.swmg.swaggerJson.basePath, '');
switch (request.swmgPathname) {
// serve swagger.json
case 'GET /swagger.json':
response.end(JSON.stringify(local.swmg.swaggerJson));
return;
}
// init swmgMethodPath
while (true) {
request.swmgMethodPath =
local.swmg.cacheDict.methodPath[request.swmgPathname];
// if swmgMethodPath exists, then break and continue
if (request.swmgMethodPath) {
request.swmgMethodPath = JSON.parse(request.swmgMethodPath);
onNext();
break;
}
// if cannot init swmgMethodPath, then default to nextMiddleware
if (request.swmgPathname === request.swmgPathnameOld) {
modeNext = Infinity;
onNext();
break;
}
request.swmgPathnameOld = request.swmgPathname;
request.swmgPathname =
request.swmgPathname.replace((/\/[^\/]+?(\/*?)$/), '/$1');
}
break;
case 2:
// init swmgParamDict
request.swmgParamDict = {};
// parse path param
tmp = request.urlParsed.pathname
.replace(local.swmg.swaggerJson.basePath, '').split('/');
request.swmgMethodPath._path.split('/').forEach(function (key, ii) {
if ((/^\{\S*?\}$/).test(key)) {
request.swmgParamDict[key.slice(1, -1)] =
decodeURIComponent(tmp[ii]);
}
});
request.swmgMethodPath.parameters.forEach(function (paramDef) {
switch (paramDef.in) {
// parse body param
case 'body':
request.swmgParamDict[paramDef.name] =
request.swmgParamDict[paramDef.name] ||
request.swmgBodyParsed;
break;
// parse formData param
case 'formData':
request.swmgParamDict[paramDef.name] =
request.swmgParamDict[paramDef.name] ||
request.swmgBodyParsed[paramDef.name];
break;
// parse header param
case 'header':
request.swmgParamDict[paramDef.name] =
request.headers[paramDef.name.toLowerCase()];