forked from vsuaste/express_graphql_model_gen
-
Notifications
You must be signed in to change notification settings - Fork 2
/
funks.js
1893 lines (1767 loc) · 54.3 KB
/
funks.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
let fs = require("fs");
const ejs = require("ejs");
const inflection = require("inflection");
const jsb = require("js-beautify").js_beautify;
const { join, parse } = require("path");
const { promisify } = require("util");
const ejsRenderFile = promisify(ejs.renderFile);
const colors = require("colors/safe");
const { getModelDatabase } = require("./lib/generators-aux");
const { getOperators } = require("./lib/operators-aux");
/**
* parseFile - Parse a json file
*
* @param {string} jFile path wher json file is stored
* @return {object} json file converted to js object
*/
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);
} catch (e) {
//msg
console.log(
colors.red("! Error:"),
"Parsing JSON model definition file:",
colors.dim(jFile)
);
console.log(colors.red("! Error name: " + e.name + ":"), e.message);
throw new Error(e);
}
return words;
};
/**
* isEmptyObject - Determines if an object is empty
*
* @param {object} obj Object to check if is empty
* @return {boolean} False if 'obj' has at least one entry, true if the object is empty.
*/
isEmptyObject = function (obj) {
for (let key in obj) {
if (obj.hasOwnProperty(key)) return false;
}
return true;
};
/**
* uncapitalizeString - set initial character to lower case
*
* @param {string} word String input to uncapitalize
* @return {string} String with lower case in the initial character
*/
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
*/
capitalizeString = function (word) {
let length = word.length;
if (length == 1) {
return word.toUpperCase();
} else {
return word.slice(0, 1).toUpperCase() + word.slice(1, length);
}
};
/**
* generateJs - Generate the Javascript code (GraphQL-schema/resolvers/Sequelize-model) using EJS templates
*
* @param {string} templateName Name of the template to use
* @param {object} options Options that the template will use
* @return {string} String of created file with specified template
*/
module.exports.generateJs = async function (templateName, options) {
let renderedStr = await ejsRenderFile(
__dirname + "/views/" + templateName + ".ejs",
options,
{}
);
let prettyStr = jsb(renderedStr);
return prettyStr;
};
/**
* attributesToString - Convert object attributes to a string separating by dots the key and value and by comma each attribute.
*
* @param {object} attributes Object attributes to convert
* @return {string} Converted object into a single string
*/
attributesToString = function (attributes) {
let str_attributes = "";
if (attributes === "undefined" || isEmptyObject(attributes))
return str_attributes;
for (key in attributes) {
str_attributes += key + ": " + attributes[key] + ", ";
}
return str_attributes.slice(0, -2);
};
/**
* attributesToJsonSchemaProperties - Convert object attributes to JSON-Schema
* properties. See http://json-schema.org
*
* @param {object} attributes Object attributes to convert
* @return {object} The generated JSON-Schema properties
*/
attributesToJsonSchemaProperties = function (attributes) {
let jsonSchemaProps = Object.assign({}, attributes);
let arrayType = [
"[String]",
"[Int]",
"[Float]",
"[Boolean]",
"[Date]",
"[Time]",
"[DateTime]",
];
for (key in jsonSchemaProps) {
if (jsonSchemaProps[key] === "String") {
jsonSchemaProps[key] = {
type: ["string", "null"],
};
} else if (jsonSchemaProps[key] === "Int") {
jsonSchemaProps[key] = {
type: ["integer", "null"],
};
} else if (jsonSchemaProps[key] === "Float") {
jsonSchemaProps[key] = {
type: ["number", "null"],
};
} else if (jsonSchemaProps[key] === "Boolean") {
jsonSchemaProps[key] = {
type: ["boolean", "null"],
};
} else if (jsonSchemaProps[key] === "Date") {
jsonSchemaProps[key] = {
anyOf: [{ isoDate: true }, { type: "null" }],
};
} else if (jsonSchemaProps[key] === "Time") {
jsonSchemaProps[key] = {
anyOf: [{ isoTime: true }, { type: "null" }],
};
} else if (jsonSchemaProps[key] === "DateTime") {
jsonSchemaProps[key] = {
anyOf: [{ isoDateTime: true }, { type: "null" }],
};
} else if (jsonSchemaProps[key] === "uuid") {
jsonSchemaProps[key] = {
type: ["uuid", "null"],
};
} else if (arrayType.includes(jsonSchemaProps[key])) {
jsonSchemaProps[key] = {
type: ["array", "null"],
};
} else {
throw new Error(`Unsupported attribute type: ${jsonSchemaProps[key]}`);
}
}
return jsonSchemaProps;
};
/**
* attributesArrayString - Get all attributes of type string
*
* @param {object} attributes Object containing the attributes to parse
* @return {array} Array of string containing only the name of the attributes which type is "string"
*/
attributesArrayString = function (attributes) {
let array_attributes = ["id"];
for (key in attributes) {
if (attributes[key] === "String") {
array_attributes.push(key);
}
}
return array_attributes;
};
/**
* getOnlyTypeAttributes - Creates an object which keys are the attributes and the value its type and also removes all spaces from both,
* the type and the attribute itself
*
* @param {object} attributes Object containing the attributes to parse
* @return {object} Object simplified, all values are strings indicating the attribute's type.
*/
getOnlyTypeAttributes = function (attributes) {
let only_type = {};
for (key in attributes) {
let key_no_spaces = key.replace(/\s+/g, "");
if (
attributes[key] &&
typeof attributes[key] === "object" &&
attributes[key].constructor === Object
) {
only_type[key_no_spaces] = attributes[key].type.replace(/\s+/g, "");
} else if (
typeof attributes[key] === "string" ||
attributes[key] instanceof String
) {
only_type[key_no_spaces] = attributes[key].replace(/\s+/g, "");
}
}
return only_type;
};
/**
* getOnlyDescriptionAttributes - Creates an object which keys are the attributes and the value its description
*
* @param {type} attributes Object containing the attributes to parse
* @return {type} Object simplified, all values are strings indicating the attribute's description.
*/
getOnlyDescriptionAttributes = function (attributes) {
let only_description = {};
for (key in attributes) {
let key_no_spaces = key.replace(/\s+/g, "");
if (
attributes[key] &&
typeof attributes[key] === "object" &&
attributes[key].constructor === Object
) {
only_description[key_no_spaces] = attributes[key].description.replaceAll(/(`)/g, "\\$1") || "";
} else if (
typeof attributes[key] === "string" ||
attributes[key] instanceof String
) {
only_description[key_no_spaces] = "";
}
}
return only_description;
};
getCassandraType = function (type) {
switch (type.toLowerCase()) {
case "string":
return "text";
case "integer":
case "int":
return "int";
case "id":
return "uuid";
case "datetime":
return "timestamp";
default:
return type;
}
};
getOnlyCassandraTypeAttributes = function (attributes, idAttribute) {
let only_type = {};
for (key in attributes) {
if (key == idAttribute) {
continue;
}
if (
attributes[key] &&
typeof attributes[key] === "object" &&
attributes[key].constructor === Object
) {
only_type[key] = attributes[key].type;
} else if (
typeof attributes[key] === "string" ||
attributes[key] instanceof String
) {
only_type[key] = getCassandraType(attributes[key]);
}
}
return only_type;
};
getCassandraAttributesType = function (
attributes,
idAttribute,
editableAttributes
) {
let only_type = {};
for (key in attributes) {
if (key == idAttribute) {
continue;
}
if (attributes[key].includes("[")) {
let arrType = attributes[key].replace(/\[|\]/gi, "");
if (editableAttributes[key]) {
only_type[key] = `list <${getCassandraType(arrType)}>`;
} else {
only_type[key] = `set <${getCassandraType(arrType)}>`;
}
} else {
only_type[key] = getCassandraType(attributes[key]);
}
}
return only_type;
};
/**
* writeSchemaCommons - Writes a 'commons.js' file into the given directory. This file contains
* general parts of the graphql schema that are common for all models.
*
* @param {string} dir_write Path of the directory where to create the commons.js file
*/
writeSchemaCommons = function (dir_write) {
let commons = `module.exports = \`
enum InputType{
Array
String
Int
Float
Boolean
Date
Time
DateTime
}
enum GenericPrestoSqlOperator {
like notLike iLike notILike regexp notRegexp iRegexp notIRegexp
eq gt gte lt lte ne between notBetween
in notIn contains notContains
or and not
}
enum MongodbNeo4jOperator {
like notLike iLike notILike regexp notRegexp iRegexp notIRegexp
eq gt gte lt lte ne
in notIn contains notContains
or and not
}
enum CassandraOperator {
eq gt gte lt lte ne
in contains
and
}
enum AmazonS3Operator {
like notLike iLike notILike
eq gt gte lt lte ne between notBetween
in notIn contains notContains
or and not
}
enum Order{
DESC
ASC
}
input paginationInput{
limit: Int!
offset: Int
}
input paginationCursorInput{
first: Int
last: Int
after: String
before: String
includeCursor: Boolean
}
type pageInfo{
startCursor: String
endCursor: String
hasPreviousPage: Boolean!
hasNextPage: Boolean!
}
scalar Date
scalar Time
scalar DateTime
scalar GraphQLJSONObject
\`;`;
try {
let file_name = dir_write + "/schemas/" + "commons.js";
fs.writeFileSync(file_name, commons);
//success
console.log(
"@@@ File:",
colors.dim(file_name),
colors.green("written successfully!")
);
} catch (e) {
//error
console.log("@@@ Error:", colors.dim(file_name), colors.red("error"));
console.log(e);
throw e;
}
};
writeIndexResolvers = async function (dir_write, models) {
//set file name
let file_name = dir_write + "/resolvers/index.js";
//generate
await generateSection("resolvers-index", { models: models }, file_name)
.then(() => {
//success
console.log(
"@@@ File:",
colors.dim(file_name),
colors.green("written successfully!")
);
})
.catch((e) => {
//error
console.log("@@@ Error:", colors.dim(file_name), colors.red("error"));
console.log(e);
throw e;
});
};
writeAcls = async function (dir_write, models, adapters) {
//set file name
let file_name = dir_write + "/acl_rules.js";
//set names
const modelsNames = models.map((item) => item[0]);
//generate
await generateSection(
"acl_rules",
{ models: modelsNames, adapters },
file_name
)
.then(() => {
//success
console.log(
"@@@ File:",
colors.dim(file_name),
colors.green("written successfully!")
);
})
.catch((e) => {
//error
console.log("@@@ Error:", colors.dim(file_name), colors.red("error"));
console.log(e);
throw e;
});
};
/**
* convertToType - Generate a string correspondant to the model type as needed for graphql schema.
*
* @param {boolean} many True if the field type in the schema corresponds to an array, false otherwise.
* @param {type} model_name Name of the model.
* @return {string} String indicating array or only the model name.
*/
convertToType = function (many, model_name) {
if (many) {
return "[ " + model_name + " ]";
}
return model_name;
};
/**
* getIndefiniteArticle - Generate the (uncapitalized) indefinite article that belongs to a given name.
*
* @param {string} name - The name that this article is to be used with
* @return {string} The indefinite article
*/
getIndefiniteArticle = function (name) {
let vowelRegex = "^[aeiouAEIOU].*";
if (name.match(vowelRegex)) {
return "an";
} else {
return "a";
}
};
/**
* getStringAttributesInCassandraSchema - Get all String attributes in a model regardless of capitalization.
* @param {object} attributes - The attributes of the schema
* @return {Array<string>} The string attributes in an array
*/
getStringAttributesInCassandraSchema = function (attributes) {
let res = [];
for (key in attributes) {
let attr = attributes[key];
if (typeof attr != "string") {
//assume a description object
if (attr["type"].toUpperCase() === "STRING") {
res.push(`'${key}'`);
}
} else if (attr.toUpperCase() === "STRING") {
res.push(`'${key}'`);
}
}
return res;
};
/**
* getOptions - Creates object with all extra info and with all data model info.
*
* @param {object} dataModel object created from a json file containing data model info.
* @return {object} Object with all extra info that will be needed to create files with templates.
*/
module.exports.getOptions = function (dataModel) {
let opts = {
name: dataModel.model,
nameCp: capitalizeString(dataModel.model),
storageType: getStorageType(dataModel),
database: getModelDatabase(dataModel),
table: inflection.pluralize(uncapitalizeString(dataModel.model)),
nameLc: uncapitalizeString(dataModel.model),
namePl: inflection.pluralize(uncapitalizeString(dataModel.model)),
namePlCp: inflection.pluralize(capitalizeString(dataModel.model)),
model_name_in_storage: dataModel.model_name_in_storage
? dataModel.model_name_in_storage
: inflection.pluralize(uncapitalizeString(dataModel.model)),
attributes: getOnlyTypeAttributes(dataModel.attributes),
useDataLoader: dataModel.useDataLoader ?? true,
cassandraAttributes: getOnlyCassandraTypeAttributes(
getOnlyTypeAttributes(dataModel.attributes),
getIdAttribute(dataModel)
),
jsonSchemaProperties: attributesToJsonSchemaProperties(
getOnlyTypeAttributes(dataModel.attributes)
),
associationsArguments: module.exports.parseAssociations(dataModel),
arrayAttributeString: attributesArrayString(
getOnlyTypeAttributes(dataModel.attributes)
),
indices: dataModel.indices,
definitionObj: dataModel,
attributesDescription: getOnlyDescriptionAttributes(dataModel.attributes),
url: dataModel.url || "",
externalIds: dataModel.externalIds || [],
regex: dataModel.regex || "",
adapterName: uncapitalizeString(dataModel.adapterName || ""),
registry: dataModel.registry || [],
idAttribute: getIdAttribute(dataModel),
indefiniteArticle: getIndefiniteArticle(dataModel.model),
indefiniteArticleCp: capitalizeString(
getIndefiniteArticle(dataModel.model)
),
cassandraRestrictions: dataModel.cassandraRestrictions,
cassandraStringAttributes: getStringAttributesInCassandraSchema(
dataModel.attributes
),
operators: getOperators(getStorageType(dataModel), dataModel.operatorSet),
};
if (opts.jsonSchemaProperties[opts.idAttribute] !== undefined) {
let props = opts.jsonSchemaProperties[opts.idAttribute];
props.type &&= props.type?.filter( type => type !== "null");
props.anyOf &&= props.anyOf?.filter( obj => obj.type !== "null");
}
opts["editableAttributesStr"] = attributesToString(
getEditableAttributes(
opts.attributes,
getEditableAssociations(opts.associationsArguments),
getIdAttribute(dataModel)
)
);
opts["editableAttributes"] = getEditableAttributes(
opts.attributes,
getEditableAssociations(opts.associationsArguments),
getIdAttribute(dataModel)
);
opts["editableCassandraAttributes"] = getEditableAttributes(
opts.cassandraAttributes,
getEditableAssociations(opts.associationsArguments),
getIdAttribute(dataModel)
);
opts["cassandraAttributesWithConvertedTypes"] = getCassandraAttributesType(
opts.attributes,
opts["idAttribute"],
opts["editableAttributes"]
);
opts["idAttributeType"] =
dataModel.internalId === undefined
? "Int"
: opts.attributes[opts.idAttribute].type ?? opts.attributes[opts.idAttribute];
opts["cassandraIdAttributeType"] = getCassandraType(
dataModel.internalId === undefined
? "Int"
: opts.idAttributeType
);
opts["defaultId"] = dataModel.internalId === undefined ? true : false;
dataModel["id"] = {
name: opts.idAttribute,
type: opts.idAttributeType,
};
opts["definition"] = JSON.stringify(definitionAttributeValuesToTypes(dataModel));
delete opts.attributes[opts.idAttribute];
return opts;
};
/**
* definitionAttributeValuesToTypes - Replace the attributes' values by their types if the values are objects with descriptions
* @param {Object} dataModelDefinition The parsed data model definition
* @returns {Object} copy A deep copy of the input, attributes' values replaced by their types
*/
definitionAttributeValuesToTypes = function (dataModelDefinition) {
let copy = JSON.parse(JSON.stringify(dataModelDefinition));
for (let attr in copy.attributes) {
let type = copy.attributes[attr];
copy.attributes[attr] = type.type ?? type;
}
return copy;
};
/**
* validateJsonFile - Does semantic validations on model options object 'opts' (EJS options).
*
* @param {object} opts Object with EJS options.
* @return {object} Object 'pass' status & existing errors array.
*/
validateJsonFile = function (opts) {
let check = {
pass: true,
errors: [],
warnings: [],
};
//check: validate external ids declare in attributes
opts.externalIds.forEach((x) => {
if (
!opts.attributes.hasOwnProperty(x) ||
!(
opts.attributes[x] === "String" ||
opts.attributes[x] === "Float" ||
opts.attributes[x] === "Int"
)
) {
//error
check.pass = false;
check.errors.push(
`ERROR: External id "${x}" has not been declared in the attributes of model ${opts.name} or is not of one of the allowed types: String, Int or Float`
);
}
});
const {
to_one,
to_many,
to_many_through_sql_cross_table,
generic_to_one,
generic_to_many,
} = opts.associationsArguments;
const parsedAssociations = to_one.concat(
to_many,
to_many_through_sql_cross_table,
generic_to_many,
generic_to_one
);
parsedAssociations.forEach((assoc) => {
//check: validate if to_one assoc with foreignKey in target model exists
// Warn user that validation e.g. unique constraint needs to be added
if (assoc.holdsForeignKey === false && assoc.type.includes("to_one")) {
check.warnings.push(
`WARNING: Association ${assoc.name} is a ${assoc.type} associations with the foreignKey in ${assoc.target}. Be sure to validate uniqueness`
);
}
//check: validate if the reverseAssociation field exist. Warn the user that
// it is mandatory for the spa
if (!assoc.reverseAssociation) {
check.warnings.push(
` WARNING: Association ${assoc.name} does not define the reverse association name in field "reverseAssociation". This field is mandatory for the single-page-app.`
);
}
});
return check;
};
getEditableAssociations = function (associations) {
let editableAssociations = [];
associations["to_one"].forEach((association) => {
if (association.keysIn !== association.target) {
editableAssociations.push(association);
}
});
//for cases many to many through foreignKey array
associations["to_many"].forEach((association) => {
if (association.keysIn !== association.target) {
editableAssociations.push(association);
}
});
return editableAssociations;
};
getEditableAttributes = function (
attributes,
parsedAssocForeignKeys,
idAttribute
) {
let editable_attributes = {};
let target_keys = parsedAssocForeignKeys.map((assoc) => {
if (assoc.type === "many_to_many" && assoc.implementation === "foreignkeys")
return assoc.sourceKey;
return assoc.targetKey;
});
for (let attrib in attributes) {
if (!target_keys.includes(attrib) && attrib !== idAttribute) {
editable_attributes[attrib] = attributes[attrib];
}
}
return editable_attributes;
};
/**
* parseAssociations - Parse associations of a given data model.
* Classification of associations will be accordingly to the type of association and storage type of target model.
*
* @param {object} dataModel Data model definition
* @return {object} Object containing explicit information needed for generating files with templates.
*/
module.exports.parseAssociations = function (dataModel) {
let associations = dataModel.associations;
associations_info = {
schema_attributes: {
many: {},
one: {},
generic_one: {},
generic_many: {},
},
//"mutations_attributes" : {},
to_one: [],
to_many: [],
to_many_through_sql_cross_table: [],
generic_to_one: [],
generic_to_many: [],
foreignKeyAssociations: {},
associations: [],
genericAssociations: [],
};
if (associations !== undefined) {
Object.entries(associations).forEach(([name, association]) => {
const type = association.type;
const implementation = association.implementation;
const schema_attributes = [
association.target,
capitalizeString(association.target),
capitalizeString(name),
];
let assoc = Object.assign({}, association);
if (
type !== "one_to_one" &&
type !== "one_to_many" &&
type !== "many_to_one" &&
type !== "many_to_many"
) {
console.error(
colors.red("Association type " + association.type + " not supported.")
);
}
// set default association fields
assoc["type"] = type;
assoc["name"] = name;
assoc["name_lc"] = uncapitalizeString(name);
assoc["name_cp"] = capitalizeString(name);
assoc["target_lc"] = uncapitalizeString(association.target);
assoc["target_lc_pl"] = inflection.pluralize(
uncapitalizeString(association.target)
);
assoc["target_pl"] = inflection.pluralize(association.target);
assoc["target_cp"] = capitalizeString(association.target); //inflection.capitalize(association.target);
assoc["target_cp_pl"] = capitalizeString(
inflection.pluralize(association.target)
);
assoc["reverseAssociation"] = association.reverseAssociation;
assoc["delete_action"] = association.deletion ?? "reject";
if (implementation !== "generic") {
// set extra association fields
assoc["targetKey"] = association.targetKey;
assoc["targetKey_cp"] = capitalizeString(association.targetKey);
if (association.sourceKey) {
assoc["sourceKey"] = association.sourceKey;
assoc["sourceKey_cp"] = capitalizeString(association.sourceKey);
}
assoc["keysIn_lc"] = uncapitalizeString(association.keysIn);
assoc["holdsForeignKey"] = false;
assoc["assocThroughArray"] = false;
assoc.targetStorageType = association.targetStorageType.toLowerCase();
association.targetStorageType =
association.targetStorageType.toLowerCase();
associations_info.associations.push(association);
associations_info.foreignKeyAssociations[name] = association.targetKey;
} else {
associations_info.genericAssociations.push(association);
}
// switch implementation types
switch (implementation) {
case "generic":
switch (type) {
case "one_to_one":
case "many_to_one":
associations_info.schema_attributes["generic_one"][name] =
schema_attributes;
associations_info["generic_to_one"].push(assoc);
break;
case "one_to_many":
case "many_to_many":
associations_info.schema_attributes["generic_many"][name] =
schema_attributes;
associations_info["generic_to_many"].push(assoc);
break;
default:
break;
}
break;
case "sql_cross_table":
if (
type !== "many_to_many" ||
association.sourceKey === undefined ||
association.keysIn === undefined
) {
console.error(
colors.red(
`ERROR: many_to_many through crosstable only allowed for relational database types with well defined cross-table`
)
);
}
associations_info.schema_attributes["many"][name] = schema_attributes;
associations_info["to_many_through_sql_cross_table"].push(assoc);
break;
case "foreignkeys":
associations_info.foreignKeyAssociations[name] =
association.targetKey;
switch (type) {
case "one_to_one":
case "many_to_one":
// schema attrtibutes
associations_info.schema_attributes["one"][name] =
schema_attributes;
if (association.sourceKey) {
assoc["assocThroughArray"] = true;
} else if (association.keysIn === dataModel.model) {
assoc["holdsForeignKey"] = true;
}
associations_info["to_one"].push(assoc);
break;
case "many_to_many":
assoc["assocThroughArray"] = true;
case "one_to_many":
associations_info.schema_attributes["many"][name] =
schema_attributes;
associations_info["to_many"].push(assoc);
if (association.sourceKey) {
assoc["assocThroughArray"] = true;
}
break;
default:
break;
}
break;
default:
if (implementation) {
console.error(
colors.red(
`ERROR: unallowed association implementation type ${implementation}.`
)
);
} else {
console.error(
colors.red(`ERROR: Please specify an implementation type.`)
);
}
}
});
}
associations_info.mutations_attributes = attributesToString(
associations_info.mutations_attributes
);
return associations_info;
};
/**
* generateAssociationsMigrations - Create files for migrations of associations between models. It could be either
* creating a new column or creating a through table.
*
* @param {object} opts Object with options required for the template that creates migrations.
* @param {string} dir_write Path where the the file will be written.
*/
generateAssociationsMigrations = function (opts, dir_write) {
// opts.associations.belongsTo.forEach( async (assoc) =>{
// if(assoc.targetStorageType === 'sql'){
// assoc["source"] = opts.table;
// assoc["cross"] = false;
// let generatedMigration = await module.exports.generateJs('create-association-migration',assoc);
// let name_migration = createNameMigration(dir_write, '', 'z-column-'+assoc.targetKey+'-to-'+opts.table);
// fs.writeFile( name_migration, generatedMigration, function(err){
// if (err)
// {
// return console.log(err);
// }else{
// console.log(name_migration+" writen succesfully!");
// }
// });
// }
// });
opts.associations.belongsToMany.forEach(async (assoc) => {
if (assoc.targetStorageType === "sql") {
assoc["source"] = opts.table;
let generatedMigration = await module.exports.generateJs(
"create-through-migration",
assoc
);
let name_migration = createNameMigration(
dir_write,
"",
"z-through-" + assoc.keysIn
);
fs.writeFile(name_migration, generatedMigration, function (err) {
if (err) {
return console.log(err);
} else {
console.log(name_migration + " writen succesfully!");
}
});
}
});
};
/**
* createNameMigration - Creates the name for the migration file accordingly to the time and date
* that the migration is created.
*
* @param {string} dir_write directory where code is being generated.
* @param {string} model_name Name of the model.
* @return {string} Path where generated file will be written.
*/
createNameMigration = function (rootDir, migrationsDir, model_name) {
let date = new Date().toISOString();
return join(
rootDir,
migrationsDir,
`${date.replace(/:/g, "_")}#${model_name}.js`
);
};
/**
* generateSection - Writes a file which contains a generated section. Each seaction has its own template.
*
* @param {string} section Name of section that will be generated (i.e. schemas, models, migrations, resolvers)
* @param {object} opts Object with options needed for the template that will generate the section
* @param {string} dir_write Path (including name of the file) where the generated section will be written as a file.
*/
generateSection = async function (section, opts, filePath) {
// const options = section.includes("schemas") ? {...opts, getOperators: getOperators} : opts;
let generatedSection = await module.exports.generateJs(
"create-" + section,
opts
);
const parsedPath = parse(filePath);