-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunks.js
More file actions
2563 lines (2244 loc) · 115 KB
/
funks.js
File metadata and controls
2563 lines (2244 loc) · 115 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
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
exports = module.exports = {};
const fs = require('fs-extra');
const path = require('path');
const inflection = require('inflection')
const {promisify} = require('util');
const ejsRenderFile = promisify( ejs.renderFile )
const colors = require('colors/safe');
const { first, template } = require('lodash');
/**
* renderTemplate - Generate the Javascript code as string using EJS templates views
*
* @param {string} templateName Name of the template view to use
* @param {object} options Options that the template will use to fill generic spaces
* @return {string} String of created file with specified template
*/
exports.renderTemplate = async function(templateName, options) {
let outFile = __dirname + '/views/pages/' + templateName + '.ejs';
try {
return await ejsRenderFile(outFile, options, {});
} catch(e) {
//msg
console.log(colors.red('@@@ Error:'), 'trying to rendering template: ', colors.dim(outFile));
throw e;
}
}
/**
* renderToFile - Given a template view it generates the code as string
* and writes the code in a output file.
*
* @param {string} outFile path to output file where code will be written
* @param {string} templateName template view name to use for generating code
* @param {object} options Options to fill the template
* @return {promise} Promise will be resolved with success message if the file is written successfully, rejected with error otherwise.
*/
exports.renderToFile = async function(outFile, templateName, options) {
let fileCont = await exports.renderTemplate(templateName, options)
p = new Promise((resolve, reject) =>{
fs.writeFile(outFile, fileCont,
function(err) {
if (err) {
reject(err);
} else {
resolve(outFile);
}
})
});
return p;
}
/**
* renderToFileSync - Given a template view it generates the code as string
* and writes the code in a output file.
*
* @param {string} outFile path to output file where code will be written
* @param {string} templateName template view name to use for generating code
* @param {object} options Options to fill the template
* @param {object} status Object with status properties. This function will set status properties on this object.
* @param {boolean} verbose Verbose option.
* @return {promise} Promise will be resolved with success message if the file is written successfully, rejected with error otherwise.
*/
exports.renderToFileSync = async function(outFile, templateName, options, status, verbose) {
let errorOnRender = false;
//generate
let genFile = await exports.renderTemplate(templateName, options)
.catch((e) => {
//flag
errorOnRender = true;
//error msg
console.log('@@@ Template:', colors.dim(templateName), 'with error.');
console.log(e);
});
//write
if(!errorOnRender) {
try {
fs.writeFileSync(outFile, genFile);
//success
if(verbose) console.log('@@@ File:', colors.dim(outFile), colors.green('written successfully!'));
} catch(e) {
errorOnRender = true;
//error msg
console.log('@@@ File:', colors.dim(outFile), ', error trying to write in file.');
console.log(e);
}
}
//check
if(errorOnRender && status && typeof status === 'object') {
//set status
status.errorOnRender = true;
if(typeof status.totalCodeGenerationErrors === 'number'){
status.totalCodeGenerationErrors++;
}
if(status.templatesWithErrors
&& Array.isArray(status.templatesWithErrors)
&& !status.templatesWithErrors.includes(templateName)) {
status.templatesWithErrors.push(templateName);
}
} else {
if(typeof status.totalFilesGenerated === 'number'){
status.totalFilesGenerated++;
}
}
}
/**
* exports - Parse input 'attributes' argument into array of arrays:
*
* @param {string} attributesStr Attributes as string
* @return {array} Array of arrays each item is as array with field name and its type (example [ [ 'name','string' ], [ 'is_human','boolean' ] ])
*/
exports.attributesArray = function(attributesStr) {
if (attributesStr !== undefined && attributesStr !== null && typeof attributesStr ===
'string') {
return attributesStr.trim().split(/[\s,]+/).map(function(x) {
return x.trim().split(':')
});
} else {
return []
}
}
/**
* typeAttributes - Collect attributes into a map with keys the attributes' types and values the attributes' names
*
* @param {array} attributesArray Array of arrays each item is as array with field name and its type
* @return {object} Map with keys the attributes' types and values the attributes' names (example: { 'string': [ 'name', 'last_name' ], 'boolean': [ 'is_human' ] })
*/
exports.typeAttributes = function(attributesArray) {
y = {};
attributesArray.forEach(function(x) {
if (!y[x[1]]) y[x[1]] = [x[0]]
else y[x[1]] = y[x[1]].concat([x[0]])
})
return y;
}
/**
* uncapitalizeString - Set initial character to lower case
*
* @param {string} word String input to uncapitalize
* @return {string} String with lower case in the initial character
*/
exports.uncapitalizeString = function(word){
let length = word.length;
if(length==1){
return word.toLowerCase();
}else{
return word.slice(0,1).toLowerCase() + word.slice(1,length);
}
}
/**
* capitalizeString - Set initial character to upper case
*
* @param {type} word String input to capitalize
* @return {type} String with upper case in the initial character
*/
exports.capitalizeString = function(word){
let length = word.length;
if(length==1){
return word.toUpperCase();
}else{
return word.slice(0,1).toUpperCase() + word.slice(1,length);
}
}
/**
* snakeToPascalCase - Converts string from snake case to pascal case.
*
* @param {type} word String input to convert.
* @return {type} String on pascal case.
*/
exports.toPascalCase = function(word){
return exports.capitalizeString(word.replace(
/([-_][a-z])/ig,
(match) => match.toUpperCase()
.replace('-', '')
.replace('_', '')
));
}
/**
* parseFile - Parse a json file
*
* @param {string} jFile path where json file is stored
* @return {object} json file converted to js object
*/
exports.parseFile = function(jFile){
let data = null;
let words = null;
//read
try {
data=fs.readFileSync(jFile, 'utf8');
} catch (e) {
//msg
console.log(colors.red('! Error:'), 'Reading JSON model definition file:', colors.dim(jFile));
console.log(colors.red('! Error name: ' + e.name +':'), e.message);
throw new Error(e);
}
//parse
try {
words=JSON.parse(data);
/**
* Check storageType: exclude adapters.
*/
if(words&&words.storageType&&typeof words.storageType === 'string')
{
switch(words.storageType.toLowerCase()){
//adapters
case 'sql-adapter':
case 'ddm-adapter':
case 'zendro-webservice-adapter':
case 'generic-adapter':
//msg
console.log(colors.white('@@ Adapter: '), colors.blue(words.model+'.'+words.adapterName), ` [${words.storageType}]... `, colors.yellow('excluded'), '');
words = null;
break;
default:
break;
}
} else {
//msg
console.log(colors.red('Error: '), "Invalid attributes found: @storageType attribute is not valid. In file:", colors.dim(jFile));
throw new Error("Invalid attributes found");
}
} catch (e) {
//msg
console.log(colors.red('Error: '), 'Parsing JSON model definition file: ', colors.dim(jFile));
throw e;
}
return words;
}
/**
* checkJsonFiles - Semantic validations related to json files.
*
* @param {string} jsonDir Input directory with json files.
* @param {array} jsonFiles Array of jsonFiles paths readed from input directory.
* @param {object} options Object with extra options used to generate output.
* @return {object} Object containing a boolean status of the validaton process (pass) and an array of errors (errors).
*/
exports.checkJsonFiles = function(jsonDir, jsonFiles, options){
let result = {
pass : true,
errors: []
}
/**
* General checks:
*/
//'jsonFiles'
if(jsonFiles.length <= 0) {
result.pass = false;
result.errors.push(`@@Error: There are no JSON files on input directory. You should specify some JSON files in order to generate the Zendro SPA.`);
} else {
/**
* Plotly checks
*/
let plotlyOptions = options.plotlyOptions;
let jsonFilesPaths = jsonFiles.map((file) => path.resolve(path.join(jsonDir, file)));
let adminModels = getAdminModels();
//genPlotly + modelsWithPlotly
if(plotlyOptions.genPlotly) {
/**
* All models should be one of those in jsonDir or an admin model name.
*/
plotlyOptions.modelsWithPlotly.forEach((file) => {
//check admin models
if(!adminModels.map(m => m.model).includes(file)
&& !jsonFilesPaths.includes(path.resolve(file))) {
result.pass = false;
result.errors.push(`@@Error: json model file '${file}' is not in the json input directory.`);
}
});
}
}
return result;
}
/**
* checkJsonDataFile - Semantic validations are carried out on the definition of the JSON model.
*
* @param {object} jsonModel Javascript object parsed from JSON model file.
* @param {object} options Object with extra options used to generate output.
* @return {object} Object containing a boolean status of the validaton process (pass) and an array of errors (errors).
*/
exports.checkJsonDataFile = function(jsonModel, options){
let result = {
pass : true,
errors: [],
warnings: 0,
}
/*
Checks:
*/
//'model'
if(!jsonModel.hasOwnProperty('model')) {
result.pass = false;
result.errors.push(`@@Error: 'model' is a mandatory field.`);
} else {
//check 'model' type
if(typeof jsonModel.model !== 'string') {
result.pass = false;
result.errors.push(`@@Error: 'model' field must be a string.`);
}
}
//'storageType'
if(!jsonModel.hasOwnProperty('storageType')) {
result.pass = false;
result.errors.push(`@@Error: 'storageType' is a mandatory field.`);
} else {
//check 'storageType' type
if(typeof jsonModel.storageType !== 'string') {
result.pass = false;
result.errors.push(`@@Error: 'storageType' field must be a string.`);
} else {
//check for valid storageType
switch(jsonModel.storageType.toLowerCase()) {
//models
case 'sql':
case 'distributed-data-model':
case 'zendro-server':
case 'generic':
//adapters
case 'sql-adapter':
case 'ddm-adapter':
case 'zendro-webservice-adapter':
case 'generic-adapter':
//ok
break;
default:
//not ok
result.pass = false;
result.errors.push(`@@Error: The attribute 'storageType' has an invalid value. One of the following types is expected: [sql, zendro-server, distributed-data-model, generic]. But '${jsonModel.storageType}' was obtained.`);
break;
}
}
}
//'attributes'
if(!jsonModel.hasOwnProperty('attributes')) {
result.pass = false;
result.errors.push(`@@Error: 'attributes' is a mandatory field.`);
} else {
//check for attributes type
if(typeof jsonModel.attributes !== 'object') {
result.pass = false;
result.errors.push(`@@Error: 'attributes' field must be an object.`);
} else {
//check for non empty attributes object
let keys = Object.keys(jsonModel.attributes);
if(keys.length === 0) {
result.pass = false;
result.errors.push(`@@Error: 'attributes' object can not be empty`);
} else {
//check for correct attributes types
for(let i=0; i<keys.length; ++i) {
switch(jsonModel.attributes[keys[i]]) {
case 'String':
case 'Int':
case 'Float':
case 'Boolean':
case 'Date':
case 'Time':
case 'DateTime':
case '[String]':
case '[Int]':
case '[Float]':
case '[Boolean]':
case '[Date]':
case '[Time]':
case '[DateTime]':
//ok
break;
default:
//not ok
result.pass = false;
result.errors.push(`@@Error: 'attribute.${keys[i]}' has an invalid type. One of the following types is expected: [String, Int, Float, Boolean, Date, Time, DateTime]. But '${jsonModel.attributes[keys[i]]}' was obtained.`);
break;
}
}
}
}
}
//'associations'
if(jsonModel.hasOwnProperty('associations')) {
//check 'associations' type
if(typeof jsonModel.associations !== 'object') {
result.pass = false;
result.errors.push(`@@Error: 'associations' field must be an object.`);
}
}
//'internalId'
if(jsonModel.hasOwnProperty('internalId')) {
//check: 'internalId' type
if(typeof jsonModel.internalId !== 'string') {
result.pass = false;
result.errors.push(`@@Error: 'internalId' attribute should have a value of type 'string', but it has one of type: '${typeof jsonModel.internalId}'`);
} else {
//check: the respective attribute has actually been defined in the "attributes" object
if(!jsonModel.attributes.hasOwnProperty(jsonModel.internalId)) {
result.pass = false;
result.errors.push(`@@Error: 'internalId' value has not been defined as an attribute. '${jsonModel.internalId}' is not an attribute.`);
} else {
//check: the respective attribute is of the allowed types String, Int, or Float
switch(jsonModel.attributes[jsonModel.internalId]) {
case 'String':
case 'Int':
case 'Float':
//ok
break;
default:
//not ok
result.pass = false;
result.errors.push(`@@Error: 'internalId' has an invalid type. One of the following types is expected: [String, Int, Float]. But '${jsonModel.attributes[jsonModel.internalId]}' was obtained.`);
break;
}
}
}
}
//'paginationType'
if(jsonModel.hasOwnProperty('paginationType')) {
//check: 'paginationType' type
if(typeof jsonModel.paginationType !== 'string') {
result.pass = false;
result.errors.push(`@@Error: 'paginationType' attribute should have a value of type 'string', but it has one of type: '${typeof jsonModel.paginationType}'`);
} else {
//check: value should be 'limitOffset' or 'cursorBased';
if(jsonModel.paginationType !== 'limitOffset' && jsonModel.paginationType !== 'cursorBased') {
result.pass = false;
result.errors.push(`@@Error: 'paginationType' value should be either 'limitOffset' or 'cursorBased', but it is: '${jsonModel.paginationType}'`);
} else {
//check: cursorBased is the only option for non-sql models
if( (jsonModel.storageType)&&(String(jsonModel.storageType).toLowerCase() !== 'sql')&&(jsonModel.paginationType !== 'cursorBased') ){
result.pass = false;
result.errors.push(`@@Error: 'limitOffset' pagination is not supported on non-sql storage types`);
}
}
}
}
//check for label field in each association
if(jsonModel.associations !== undefined){
Object.entries(jsonModel.associations).forEach( ([name, association], index) =>{
//skip generic associations
if(association.type === 'generic_to_one' || association.type === 'generic_to_many') return;
//check
if(association.label === undefined || association.label === ''){
//warning
console.log(colors.yellow("@@Warning: 'label' is not defined"), 'on model:', colors.blue(jsonModel.model), 'on associaton:', colors.blue(name));
result.warnings++;
}
})
}
return result;
}
/**
* fillOptionsForViews - Creates object with all the information about data model that templates will use.
*
* @param {object} fileData Object originally created from a json file containing data model info.
* @param {string} filePath JSON model file path.
* @param {object} options Object with extra options used to generate output.
* @return {object} Object with all data model info that will be used to create files with templates.
*/
exports.fillOptionsForViews = function(fileData, filePath, options){
//get associations options
let results = parseAssociationsFromFile(fileData);
let associations = results.associations;
let warnings = results.warnings;
//set options used by EJS templates
let opts = {
baseUrl: fileData.baseUrl,
name: fileData.model,
nameLc: exports.uncapitalizeString(fileData.model),
namePl: inflection.pluralize(exports.uncapitalizeString(fileData.model)),
namePlLc: inflection.pluralize(exports.uncapitalizeString(fileData.model)),
namePlCp: inflection.pluralize(exports.capitalizeString(fileData.model)),
nameCp: exports.capitalizeString(fileData.model),
nameOnPascal: exports.toPascalCase(fileData.model),
attributesArr: attributesArrayFromFile(fileData.attributes),
attributesArrWithoutTargetKeys: attributesWithoutTargetKeysArrayFromFile(fileData.attributes, associations.ownForeignKeysArr),
typeAttributes: exports.typeAttributes(attributesArrayFromFile(fileData.attributes)),
belongsTosArr: associations.belongsTos,
hasManysArr: associations.hasManys,
sortedAssociations: associations.sortedAssociations,
sortedAssociatedModels : associations.sortedAssociatedModels,
ownForeignKeysArr: associations.ownForeignKeysArr,
hasOwnForeingKeys: associations.hasOwnForeingKeys,
hasToManyAssociations: associations.hasToManyAssociations,
internalId: getInternalId(fileData),
internalIdType: getInternalIdType(fileData),
isDefaultId: (fileData.internalId) ? false : true,
paginationType: getPaginationType(fileData),
storageType: fileData.storageType,
//Plotly
withPlotly: getWithPlotly(options, filePath),
standalonePlotly: options.plotlyOptions.standalonePlotly,
//Warnings
warnings,
}
return opts;
}
/**
* addKeyRelationName - Adds 'keyRelationName' name-attributes to each association defined on each model.
* This key name is a unique name that identifies a relation between two models and is composed as follows:
*
* Case: to_many || to_one:
* <keyIn>_<targetKey>
*
* Case: to_many_through_sql_cross_table:
* <keysIn>
*
* Case: generic_to_one || generic_to_many
* <modelName>_<relationName>
*
* @param {array} opts Array of already calculated EJS model options.
* @param {object} status Object with status properties. This function will set status properties on this object.
*/
exports.addKeyRelationName = function(opts, status) {
let warningsA = []; //target model not found
let warningsB = []; //peer association not found
let errorsA = []; //check A: keyIn should be the same in both peers
let errorsB = []; //check B: association type: should be to_one || to_many
let errorsC = []; //check C: peerA.model should be = peerB.targetModel
let errorsD = []; //check D: peerA.targetKey should be = peerB.sourceKey
let errorsE = []; //check E: peerA.sourceKey should be = peerB.targetKey
let errorsF = []; //check F: target model not found && is many_to_many
let errorsG = []; //check G: peer association not found && is many_to_many
//for each model
opts.forEach( (opt) => {
//for each association
opt.sortedAssociations.forEach( (association) => {
/**
* Set keyRelationName attribute.
*/
if(association.type === 'to_one' || (association.type === 'to_many' && association.typeB !== 'assocThroughArray')) {
association.keyRelationName = association.keyIn+'_'+association.targetKey;
} else if(association.type === 'to_many' && association.typeB === 'assocThroughArray') {
association.keyRelationName = association.targetModel+'_'+association.peerTargetKey;
} else if(association.type === 'to_many_through_sql_cross_table') {
association.keyRelationName = association.keysIn;
} else if(association.type === 'generic_to_one' || association.type === 'generic_to_many') {
association.keyRelationName = opt.name+'_'+association.relationName;
}
/**
* Checks
* - Target model
* - Peer relation
* - Unique <keyIn> + <targetKey>
* - Unique <keysIn>
*/
//find target model
let foundTargetModel = false;
for(let i=0; i<opts.length && !foundTargetModel; i++) {
/**
* Case: target model found
*/
if(association.targetModel === opts[i].name) {
foundTargetModel = true;
//find peer association
let foundPeerAssociation = false;
for(let j=0; j<opts[i].sortedAssociations.length && !foundPeerAssociation; j++) {
if(association.type === 'to_one' || (association.type === 'to_many' && association.typeB !== 'assocThroughArray')) {
/**
* Case: peer association found
*/
if(opts[i].sortedAssociations[j].targetModel === opt.name
&& opts[i].sortedAssociations[j].targetKey === association.targetKey) {
foundPeerAssociation = true;
//check A: keyIn should be the same in both peers
if(opts[i].sortedAssociations[j].keyIn !== association.keyIn) {
//error
errorsA.push({
model: opt.name,
association: association.relationName,
targetKey: association.targetKey,
keyIn: association.keyIn,
targetModel: association.targetModel,
peerAssociationName: opts[i].sortedAssociations[j].relationName,
peerAssociationKeyIn: opts[i].sortedAssociations[j].keyIn,
});
}
//check B: association type: should be to_one || to_many
if(opts[i].sortedAssociations[j].type !== 'to_one' && opts[i].sortedAssociations[j].type !== 'to_many') {
//error
errorsB.push({
model: opt.name,
association: association.relationName,
targetKey: association.targetKey,
type: association.type,
targetModel: association.targetModel,
peerAssociationName: opts[i].sortedAssociations[j].relationName,
peerAssociationType: opts[i].sortedAssociations[j].type,
});
}
}//else: nothing to check
} else if(association.type === 'to_many_through_sql_cross_table') {
/**
* Case: same keysIn found
*/
if(opts[i].sortedAssociations[j].keysIn === association.keysIn) {
foundPeerAssociation = true;
//set peer association names
association.peerAssociationName = opts[i].sortedAssociations[j].relationName;
association.peerAssociationNameCp = opts[i].sortedAssociations[j].relationNameCp;
association.peerAssociationNameLc = opts[i].sortedAssociations[j].relationNameLc;
association.peerAssociationNameOnPascal = opts[i].sortedAssociations[j].relationNameOnPascal;
/**
* Check: crossed attributes
*
* (C) peerA.model should be = peerB.targetModel
* (D) peerA.targetKey should be = peerB.sourceKey
* (E) peerA.sourceKey should be = peerB.targetKey
*/
if(opts[i].sortedAssociations[j].targetModel !== opt.name) {
//error: on check: (C)
errorsC.push({
model: opt.name,
association: association.relationName,
targetKey: association.targetKey,
keysIn: association.keysIn,
targetModel: association.targetModel,
peerAssociationName: opts[i].sortedAssociations[j].relationName,
peerAssociationTargetModel: opts[i].sortedAssociations[j].targetModel,
});
}
if(opts[i].sortedAssociations[j].sourceKey !== association.targetKey) {
//error: on check: (D)
errorsD.push({
model: opt.name,
association: association.relationName,
targetKey: association.targetKey,
keysIn: association.keysIn,
targetModel: association.targetModel,
peerAssociationName: opts[i].sortedAssociations[j].relationName,
peerAssociationSourceKey: opts[i].sortedAssociations[j].sourceKey,
});
}
if(opts[i].sortedAssociations[j].targetKey !== association.sourceKey) {
//error: on check: (E)
errorsE.push({
model: opt.name,
association: association.relationName,
sourceKey: association.sourceKey,
keysIn: association.keysIn,
targetModel: association.targetModel,
peerAssociationName: opts[i].sortedAssociations[j].relationName,
peerAssociationTargetKey: opts[i].sortedAssociations[j].targetKey,
});
}
}//end: Case: same keysIn found
}
}//end: for each association on target model: find peer
/**
* Checks: peer association not found
*
* (B) peer association not found on to_one or to_many: warning
* (G) peer association not found on many_to_many: error
*/
if(!foundPeerAssociation) {
if(association.type === 'to_many_through_sql_cross_table') {
//error: on check: (G)
errorsG.push({
model: opt.name,
association: association.relationName,
keysIn: association.keysIn,
targetModel: association.targetModel,
});
}else {//warning: on check (B)
if(!(association.type === 'to_many' && association.typeB === 'assocThroughArray')) {
warningsB.push({model: opt.name, association: association.relationName, targetKey: association.targetKey, targetModel: association.targetModel});
}
}
}
}//end: Case: target model found
}//end: for each model: find target model
/**
* Checks: target model not found
*
* (A) target model not found on to_one or to_many: warning
* (F) target model not found on many_to_many: error
*/
if(!foundTargetModel) {
if(association.type === 'to_many_through_sql_cross_table') {
//error: on check: (F)
errorsG.push({
model: opt.name,
association: association.relationName,
keysIn: association.keysIn,
targetModel: association.targetModel,
});
}else {//warning: on check (A)
warningsA.push({model: opt.name, association: association.relationName, targetModel: association.targetModel});
}
}
}); //end: for each association: add keyRelationName & do checks.
}); //end: for each model: add keyRelationName & do checks on each association.
/**
* Report warnings.
* Report & throw errors.
*/
//target model not found
warningsA.forEach((e) => {
console.log(colors.yellow('@@Warning: Incomplete association definition'), 'on model:', colors.blue(e.model), 'on associaton:', colors.blue(e.association), '- Association target model:', colors.yellow(e.targetModel), 'not found.');
});
//peer association not found
warningsB.forEach((e) => {
console.log(colors.yellow('@@Warning: Incomplete association definition'), 'on model:', colors.blue(e.model), 'on associaton:', colors.blue(e.association), '- Peer association on target key:', colors.yellow(e.targetKey), 'not found on target model:', colors.yellow(e.targetModel));
});
//set status totalWarnings
status.totalWarnings += (warningsA.length + warningsB.length);
//errorsA: keyIn should be the same in both peers
errorsA.forEach((e) => {
console.log(colors.yellow('@@Error: Incorrect association definitions peer'), 'on model:', colors.blue(e.model), 'on associaton:', colors.blue(e.association), '- <keyIn> attribute should be the same in an associaton definitions peer, but got: <keyIn>:', colors.blue(e.keyIn), 'with: <keyIn>:', colors.yellow(e.peerAssociationKeyIn), 'in peer:', colors.yellow(e.targetModel+'-'+e.peerAssociationName));
});
//errorsB: association type: should be to_one || to_many
errorsB.forEach((e) => {
console.log(colors.yellow('@@Error: Incorrect association definitions peer'), 'on model:', colors.blue(e.model), 'on associaton:', colors.blue(e.association), '- <association.type> should be <to_one> || <to_many> in peer associaton definition, but got: <type>:', colors.blue(e.type), 'with: <type>:', colors.yellow(e.peerAssociationType), 'in peer:', colors.yellow(e.targetModel+'-'+e.peerAssociationName));
});
//errorsC: peerA.model should be = peerB.targetModel
errorsC.forEach((e) => {
console.log(colors.yellow('@@Error: Incorrect association definitions peer'), 'on model:', colors.blue(e.model), 'on associaton:', colors.blue(e.association), '- <targetModel> in peer association should be equal to this <modelName>, but got: <targetModel>:', colors.yellow(e.peerAssociationTargetModel), 'in peer:', colors.yellow(e.targetModel+'-'+e.peerAssociationName));
});
//errorsD: peerA.targetKey should be = peerB.sourceKey
errorsD.forEach((e) => {
console.log(colors.yellow('@@Error: Incorrect association definitions peer'), 'on model:', colors.blue(e.model), 'on associaton:', colors.blue(e.association), 'with <targetKey>:', colors.blue(e.targetKey), '- <sourceKey> in peer association should be equal to <targetKey> in this association, but got: <sourceKey>:', colors.yellow(e.peerAssociationSourceKey), 'in peer:', colors.yellow(e.targetModel+'-'+e.peerAssociationName));
});
//errorsE: peerA.sourceKey should be = peerB.targetKey
errorsE.forEach((e) => {
console.log(colors.yellow('@@Error: Incorrect association definitions peer'), 'on model:', colors.blue(e.model), 'on associaton:', colors.blue(e.association), 'with <sourceKey>:', colors.blue(e.sourceKey), '- <targetKey> in peer association should be equal to <sourceKey> in this association, but got: <targetKey>:', colors.yellow(e.peerAssociationTargetKey), 'in peer:', colors.yellow(e.targetModel+'-'+e.peerAssociationName));
});
//errorsF: target model not found on many_to_many
errorsF.forEach((e) => {
console.log(colors.yellow('@@Error: Incomplete association definition'), 'on model:', colors.blue(e.model), 'on associaton:', colors.blue(e.association), 'with <keysIn>:', colors.blue(e.keysIn), '- Association target model:', colors.yellow(e.targetModel), 'not found.');
});
//errorsG: peer association not found on many_to_many
errorsG.forEach((e) => {
console.log(colors.yellow('@@Error: Incomplete association definition'), 'on model:', colors.blue(e.model), 'on associaton:', colors.blue(e.association), 'with <keysIn>:', colors.blue(e.keysIn), '- Peer association on keysIn:', colors.yellow(e.keysIn), 'not found on target model:', colors.yellow(e.targetModel));
});
//throws if there is any error
if(errorsA.length > 0 || errorsB.length > 0 || errorsC.length > 0 || errorsD.length > 0 || errorsE.length > 0 || errorsF.length > 0 || errorsG.length > 0) {
throw new Error("Incorrect association definition");
}
}
/**
* addExtraAttributesAssociations - Adds extra attributes to each association defined on each model.
*
* @param {array} opts Array of already calculated EJS options.
*/
exports.addExtraAttributesAssociations = function(opts) {
//for each model
opts.forEach( (opt) => {
//for each association
opt.sortedAssociations.forEach( (association, aindex, aarray) => {
//find target model
let found = false;
for(let i=0; !found && i<opts.length; i++) {
if(association.targetModel === opts[i].name) {
found = true;
/**
* Add extra attributes:
*/
//set internalId
association.internalId = opts[i].internalId;
//set internalIdType
association.internalIdType = opts[i].internalIdType;
//set isDefaultId
association.isDefaultId = opts[i].isDefaultId;
//set paginationType
association.paginationType = opts[i].paginationType;
}
}
})
});
}
/**
* attributesArrayFromFile - Given a object containing attributes description, this function will
* convert it to an array of arrays, where each item is as array with field name and its type (example [ [ 'name','string' ], [ 'is_human','boolean' ] ])
*
* @param {object} attributes Object with keys the name of the field and value its type.
* @return {array} array of arrays, where each item is as array with field name and its type (example [ [ 'name','string' ], [ 'is_human','boolean' ] ])
*/
attributesArrayFromFile = function(attributes){
let attArray = []
for(attr in attributes){
attArray.push([ attr, attributes[attr] ]);
}
return attArray;
}
/**
* attributesWithoutTargetKeysArrayFromFile - Given a object containing attributes description,
* this function will convert it to an array of arrays, where each item is as array with field
* name and its type (example [ [ 'name','string' ], [ 'is_human','boolean' ] ]).
* Own target keys given on @ownTargetKeys will be excluded.
*
* @param {object} attributes Object with keys the name of the field and value its type.
* @param {object} attrownTargetKeysibutes Object with keys the name of the field and value its type.
* @return {array} Array of arrays, where each item is as array with field name and its type
* (example [ [ 'name','string' ], [ 'is_human','boolean' ] ]).
*/
attributesWithoutTargetKeysArrayFromFile = function(attributes, ownTargetKeys){
let attArray = []
for(attr in attributes){
if(!ownTargetKeys.includes(attr))
{
attArray.push([ attr, attributes[attr] ]);
}
}
return attArray;
}
/**
* parseAssociationsFromFile - Parse associations description for a given model
*
* @param {object} fileData Object parsed from a model JSON file definition.
* @return {object} Associations classified as 'belongsTos' and 'hasManys'. Each association will contain all extra information required by the tamplatees views.
*/
parseAssociationsFromFile = function(fileData){
//check
let results = checkAssociations(fileData); // !throws on error
let warnings = results.warnings;
let associations = fileData.associations;
let assoc = {
"belongsTos" : [],
"hasManys" : [],
"sortedAssociations" : [],
"sortedAssociatedModels" : [],
"ownForeignKeysArr" : [],
hasOwnForeingKeys: false,
hasToManyAssociations: false,
}
if(associations!==undefined){
Object.entries(associations).forEach( ([name, association]) =>{
let type = association.type;
let sqlType = getSqlType(association, name);
//base association attributes
let baa = {
"type" : type,
"sqlType" : sqlType,
"typeB" : sqlType,
"relationName" : name,
"relationNameCp": exports.capitalizeString(name),
"relationNameLc": exports.uncapitalizeString(name),
"relationNameOnPascal": exports.toPascalCase(name),
"targetModel": association.target,
"targetModelLc": exports.uncapitalizeString(association.target),
"targetModelPlLc": inflection.pluralize(exports.uncapitalizeString(association.target)),
"targetModelCp": exports.capitalizeString(association.target),
"targetModelPlCp": inflection.pluralize(exports.capitalizeString(association.target)),
"targetModelOnPascal": exports.toPascalCase(association.target),
"label" : association.label,
"sublabel" : association.sublabel
}
//sqlType dependent attributes
switch (sqlType) {
case "belongsTo":
assoc.hasOwnForeingKeys = true;
assoc.ownForeignKeysArr.push(association.targetKey);
baa.foreignKey = association.targetKey;
baa.targetKey = association.targetKey;
baa.keyIn = association.keyIn;
break;
case "hasOne":
baa.foreignKey = association.targetKey;
baa.targetKey = association.targetKey;
baa.keyIn = association.keyIn;
if(association.keyIn === fileData.model) {
assoc.hasOwnForeingKeys = true;
assoc.ownForeignKeysArr.push(association.targetKey);
}
break;
case "belongsToMany":
baa.keysIn = association.keysIn;
baa.sourceKey = association.sourceKey;
baa.targetKey = association.targetKey;
break;
case "hasMany":
baa.foreignKey = association.targetKey;
baa.targetKey = association.targetKey;
baa.keyIn = association.keyIn;
break;
case "generic":
break;
case "assocThroughArray":
baa.foreignKey = association.sourceKey;
baa.targetKey = association.sourceKey;
baa.keyIn = association.keyIn;
baa.peerTargetKey = association.targetKey;
assoc.hasOwnForeingKeys = true;
assoc.ownForeignKeysArr.push(association.sourceKey);
break;
default:
//unknown type
console.log(colors.red('@@Error on association:'), colors.blue(name), '- Association has insconsistent key attributes.');
throw new Error("Inconsistent attributes found");
}
if(type==='to_one' || type==='generic_to_one'){
assoc.belongsTos.push(baa);
assoc.sortedAssociations.push(baa);
}else if(type==="to_many" || type==="to_many_through_sql_cross_table" || type==='generic_to_many'){
assoc.hasManys.push(baa);
assoc.sortedAssociations.push(baa);
assoc.hasToManyAssociations = true;
}else{
//unknown type
console.log(colors.red('Error: '), "Association type:", colors.dim(association.type), colors.yellow("not supported"));
throw new Error("Invalid attributes found");
}
});