-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmeta.js
9409 lines (7744 loc) · 415 KB
/
meta.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
/*
/
/ For managing data dictionary and for building the accounting system from metadata.
/ Tables must be named in the singular and in camelCase. "customerOrder not customerorders"
/ Numerals may not be used in field names except to append a zero onto the field names of
/ objects which are intended to be duplicated. For instance phone0 in the contact table when
/ a contact may have many phone numbers nested in the document.
/ Use "streetOne" not "street1" when field names must include numbers.
/ Do not use any punctuation in table and field names. Use only A to Z or a to z.
/
*/
"use strict";
// Dependencies
const fs = require('fs');
const path = require('path');
const { pipeline, Readable, Writable } = require('stream');
const StringDecoder = require('string_decoder').StringDecoder;
const helpers = require('./aHelpers');
// Define the container to hold data and functions for managing the data dictionary and for building the accounting system.
var meta = {};
// Define the base directory of the accounting folder.
meta.baseDir = path.join(__dirname, '/../accounting/');
// Define the branch of the meta object which will hold the functions used to build the accounting system.
meta.build = {}
// Define a function which builds server-side handlers that contain logic for serving webpages which
// are used to interact with tables. Also built by this function are the post, put, and get handlers
// which are the server side logic for interacting with tables.
meta.build.serverSideLogic = function(metadataId)
{
// This object tells the getMostRecent function which record to retrive in the data dictionary (metadata.json)
let dataObject = {};
// We are not trying to write to the table so no need to enforce uniqueness.
// Since this field is never empty in metadata.json, an empty string will pass the uniqueness test in getMostRecent().
dataObject.uniqueField01Value = "";
dataObject.uniqueField01Name = "tableName";
dataObject.path = '/database/dbMetadata/metadata.json';
dataObject.queryString = 'WHERE:;metadataId:;MatchesExactly:;' + metadataId + ':;';
let recordObject;
let htmlString = "";
// Collect information about the webpage from the metadata.
// 1. Look in metadata.json - Read the object for the given metadataId.
helpers.getMostRecent(dataObject, function(errorFromGetMostRecent, payload)
{
if(!errorFromGetMostRecent) // Got the most recent record from getMostRecent
{
// Used to decode the payload buffer into readable text.
let decoder = new StringDecoder('utf8');
// This instance of the Writable object gives us a place for a callback to run when the payload is received.
const writable = new Writable();
// Called by pipeline below.
// Here is where we process the single line of json returned in the payload to make the the handlers.
writable.write = function(payload)
{
let stringContainer = '';
stringContainer = stringContainer + decoder.write(payload);
recordObject = JSON.parse(stringContainer);
// All the metadata for the table is in record object.
// Assemble the webpage string from the metadata in recordObject.
let tableNameInTitleCase = recordObject.tableName[0].toUpperCase() + recordObject.tableName.slice(1);
// Figure out how many directories deep the table is in relation to the root directory of the application.
// To do this we count the slashes in the directory path for the table we are handling and add two.
// Thats's how many instances of "../" we need to add the require string to reach code in the lib directory.
let nestLevel = recordObject.directory.split('/').length + 2;
let nestString = ""
for (let loopCount = 0; loopCount < nestLevel - 1; loopCount = loopCount + 1)
{
nestString = nestString + "../";
}
// End of: Figure out how many directories deep...
htmlString = htmlString +
`/*
/ Handlers for the "${recordObject.tableName}" table.
/ This program was built by meta.js starting at yx52pvsi0kn9p5o46hrq
/ Any changes made to this program will be overwritten next time the application is generated.
/ Make your changes in the generator meta.js or in the data dictionary metadata.json
*/
"use strict";
// Dependencies
const fs = require('fs');
const readline = require('readline');
const { pipeline, Readable, Writable } = require('stream');
const StringDecoder = require('string_decoder').StringDecoder;
const _data = require('${nestString}lib/aData');
const helpers = require('${nestString}lib/aHelpers');
// Create a container for all the handlers
let ${recordObject.tableName} = {};
// Define the handler function that serves up the HTML page for searching and listing ${recordObject.tableName} records.
// Behavior from meta.js at gg9ec14lo9rqjk7kxz7f
${recordObject.tableName}.serveListPage = function(data, callback)
{
// Reject any request that isn't a get
if(data.method == 'get')
{
// The following values will be inserted into the webpage at the corresponding key locations in the templates.
var templateData =
{
'head.title' : '${tableNameInTitleCase} List',
'body.class' : '${recordObject.tableName}List',
'tableName':'${recordObject.tableName}',
"tableLabel":"${tableNameInTitleCase}",
'head.clientCode' : '', // The HTML header template must see something or an empty string.
};
// Read in a template as a string
helpers.getTemplate('../accounting/${recordObject.directory}/${recordObject.tableName}List', templateData, function(errorGetTemplate, str)
{
if(!errorGetTemplate && str) // If there were no errors and a template was returned
{
// Add the universal header and footer.
helpers.addUniversalTemplates(str, templateData, function(errorAddUnivTemplates, str)
{
if(!errorAddUnivTemplates && str) // if no error and template was returned:
{
// Return that page as html
callback(200, str, 'html');
}
else // there was an error or the concatenated templates were not returned.
{
helpers.log
(
5,
'${helpers.createRandomString(20)}' + '\\n' +
'There was an error or the concatenated templates were not returned.' + '\\n' +
'This was the error:' + '\\n' +
JSON.stringify(errorAddUnivTemplates) + '\\n'
);
callback(500, undefined, 'html');
}
}); // End of: helpers.addUniversalTemplates(str...
} // End of: If there were no errors and a template was returned
else // There was an error or no template was returned.
{
helpers.log
(
5,
'${helpers.createRandomString(20)}' + '\\n' +
'There was an error or no template was returned.' + '\\n' +
'This was the error:' + '\\n' +
JSON.stringify(errorGetTemplate) + '\\n'
);
// Send back status code for Internal Server Error, an undefined payload, and contentType of html.
callback(500, undefined, 'html');
}
}); // End of: call to helpers.getTemplate(...
} // End of: if the method is get
else // Method not get. Only gets allowed.
{
helpers.log
(
5,
'${helpers.createRandomString(20)}' + '\\n' +
'Method not get. Only gets allowed.' + '\\n'
);
// Send back status code for Not Allowed, an undefined payload, and contentType of html,
callback(405, undefined, 'html');
} // End of: else method not a get
}; // End of: ${recordObject.tableName}.serveListPage = function(data, callback){...}
// End of:// Define the handler function that serves up the HTML page for searching and listing ${recordObject.tableName} records.
// Define the handler function that serves up the HTML page for creating new ${recordObject.tableName} records.
// Behavior from meta.js at xenz5eipqot8nym0eev3
${recordObject.tableName}.serveAddPage = function(data, callback)
{
// Reject any request that isn't a get
if(data.method == 'get')
{
// The following values will be inserted into the webpage at the corresponding key locations in the templates.
var templateData =
{
'head.title' : 'Create a New ${tableNameInTitleCase}',
'head.description' : 'For creating a new ${recordObject.tableName} record',
'body.class' : '${recordObject.tableName}Add',
'head.clientCode' : '', // The HTML header template must see something or an empty string.
};
// Read in a template as a string
helpers.getTemplate('../accounting/${recordObject.directory}/${recordObject.tableName}Add', templateData, function(errorGetTemplate, str)
{
if(!errorGetTemplate && str) // If there were no errors and a template was returned
{
// Add the universal header and footer.
helpers.addUniversalTemplates(str, templateData, function(errorAddUnivTemplates, str)
{
if(!errorAddUnivTemplates && str) // if no error and template was returned:
{
// Return that page as html
callback(200, str, 'html');
}
else // there was an error or the concatenated templates were not returned.
{
helpers.log
(
5,
'${helpers.createRandomString(20)}' + '\\n' +
'There was an error or the concatenated templates were not returned.' + '\\n' +
'This was the error:' + '\\n' +
JSON.stringify(errorAddUnivTemplates) + '\\n'
);
callback(500, undefined, 'html');
}
}); // End of: helpers.addUniversalTemplates(str...
} // End of: If there were no errors and a template was returned
else // There was an error or no template was returned.
{
helpers.log
(
5,
'${helpers.createRandomString(20)}' + '\\n' +
'There was an error or no template was returned.' + '\\n' +
'This was the error:' + '\\n' +
JSON.stringify(errorGetTemplate) + '\\n'
);
// Send back status code for Internal Server Error, an undefined payload, and contentType of html.
callback(500, undefined, 'html');
}
}); // End of: call to helpers.getTemplate(...
} // End of: if the method is get
else // Method not get. Only gets allowed.
{
helpers.log
(
5,
'${helpers.createRandomString(20)}' + '\\n' +
'Method not get. Only gets allowed.' + '\\n'
);
// Send back status code for Not Allowed, an undefined payload, and contentType of html,
callback(405, undefined, 'html');
} // End of: else method not a get
}; // End of: ${recordObject.tableName}.serveAddPage = function(data, callback){...}
// End of: Define the handler function that serves up the HTML page for creating new ${recordObject.tableName} records.
// Define the handler function that serves up the HTML page for editing ${recordObject.tableName} records.
// Behavior from meta.js at 2a4tb24fsq3de66ti8c4
${recordObject.tableName}.serveEditPage = function(data, callback)
{
// Reject any request that isn't a get
if(data.method == 'get')
{
// The following values will be inserted into the webpage at the corresponding key locations in the templates.
var templateData =
{
'head.title' : 'Edit a ${tableNameInTitleCase}',
'body.class' : '${recordObject.tableName}Edit',
'selected.${recordObject.tableName}Id' : data.queryStringObject.${recordObject.tableName}Id,
'head.clientCode' : '', // The HTML header template must see something or an empty string.
};
// Read in a template as a string
helpers.getTemplate('../accounting/${recordObject.directory}/${recordObject.tableName}Edit', templateData, function(errorGetTemplate, str)
{
if(!errorGetTemplate && str) // If there were no errors and a template was returned
{
// Add the universal header and footer.
helpers.addUniversalTemplates(str, templateData, function(errorAddUnivTemplates, str)
{
if(!errorAddUnivTemplates && str) // if no error and template was returned:
{
// Return that page as html
callback(200, str, 'html');
}
else // there was an error or the concatenated templates were not returned.
{
helpers.log
(
5,
'${helpers.createRandomString(20)}' + '\\n' +
'There was an error or the concatenated templates were not returned.' + '\\n' +
'This was the error:' + '\\n' +
JSON.stringify(errorAddUnivTemplates) + '\\n'
);
callback(500, undefined, 'html');
}
}); // End of: helpers.addUniversalTemplates(str...
} // End of: If there were no errors and a template was returned
else // There was an error or no template was returned.
{
helpers.log
(
5,
'${helpers.createRandomString(20)}' + '\\n' +
'There was an error or no template was returned.' + '\\n' +
'This was the error:' + '\\n' +
JSON.stringify(errorGetTemplate) + '\\n'
);
// Send back status code for Internal Server Error, an undefined payload, and contentType of html.
callback(500, undefined, 'html');
}
}); // End of: call to helpers.getTemplate(...
} // End of: if the method is get
else // Method not get. Only gets allowed.
{
helpers.log
(
5,
'${helpers.createRandomString(20)}' + '\\n' +
'Method not get. Only gets allowed.' + '\\n'
);
// Send back status code for Not Allowed, an undefined payload, and contentType of html,
callback(405, undefined, 'html');
} // End of: else method not a get
}; // End of: ${recordObject.tableName}.serveEditPage = function(data, callback){...}
// End of: Define the handler function that serves up the HTML page for editing ${recordObject.tableName} records.
// Router for ${recordObject.tableName} functions
// Define a function which calls the requested get, post, put, or delete subhandler function for ${recordObject.tableName}
// and passes to the chosen subhandler the client's request object and the callback function.
// Behavior from meta.js at lw39etuyhw7wb82hv9ct
${recordObject.tableName}.${recordObject.tableName} = function(data, callback)
{
// Create an array of acceptable methods.
var acceptableMethods = ['post', 'get', 'put'];
// if the requested method is one of the acceptable methods:
if (acceptableMethods.indexOf(data.method) > -1)
{
// then call the appropriate ${recordObject.tableName} subhandler.
${recordObject.tableName}._${recordObject.tableName}[data.method](data, callback);
}
// Otherwise the method was not one of the acceptable methods:
else
{
helpers.log
(
5,
'${helpers.createRandomString(20)}' + '\\n' +
'The method was not one of the acceptable methods' + '\\n'
);
// so send back status 405 (Not Allowed).
callback(405);
}
}; // End of: ${recordObject.tableName}.${recordObject.tableName} = function(data, callback){...}
//End of: Router for ${recordObject.tableName} functions
// Create a subobject within the handlers object for the ${recordObject.tableName} submethods (post, get, put, and delete)
${recordObject.tableName}._${recordObject.tableName} = {};
`
// ???? Will need to return here frequently to copy variables from this area.
// Creating the POST, PUT, and GET handlers.
// Start of: Collect information about the fields.
// Create one defaultElements object combining the key/value pairs of all the defaultElements objects that might exist in a table.
// These defaultElements may not have the same name as the table fields.
// For instance: The "hashedPassword" field in the user file is fed from the "password" defaultElement.
// We do this because the password is hashed before it is written to the table.
// hashedPassword is a calculated field. It is not fed directly from the user's input.
// Some of these fields may be objects that contain more fields and we will need the pathName to all of them.
// The pathNames to all these fields will be pushed into this array.
let keysOfFieldsArray = [];
let fieldsObject = recordObject.fields;
// Loop thorough the top level of fields object - drilling into it as required.
for (let fieldKey in fieldsObject)
{
// If this top level field is an object containing more fields inside...
if(fieldsObject[fieldKey][fieldKey + "0"])
{
// Declare a function that we will use to drill into the object.
function drillIntoObject(address, objKey, objectNestLevel, previousPath)
{
// if the subfield is also an object then this function calls itself using the subfield parameters.
// This will continue drilling in until we are at the end of the branches
if(address[objKey][objKey + "0"])
{
// Check each property of the subobject to see if it too is an object.
for (let property in address[objKey][objKey + "0"])
{
// If the property is also an object
if(address[objKey][objKey + "0"][property][property + "0"])
{
// This function calls itself so as to go deeper into the object
drillIntoObject(address[objKey][objKey + "0"], property, objectNestLevel + 1, previousPath + objKey + "_" + objKey + "0_");
}
else // This property is not an object. We are at the end of the branch where we encounter a data field.
{
// Assemble the path through the current object to the current data field.
let objectPath = objKey + "_" + objKey + "0" + "_" + property;
// If the current object is nested then prepend the path to include the parent objects.
objectPath = previousPath.length === 0 ? objectPath : previousPath + objectPath;
keysOfFieldsArray.push(objectPath);
} // End of: else - This property is not an object.
} // End of: for-let Check each property of the subobject to see if it too is an object.
} // End of: if the subfield is also an object
}; // End of: function drillIntoObject(address, objKey, objectNestLevel, previousPath){...}
// Keep track of how deep we have drilled into the object.
let objectNestLevel = 1;
// Call the function defined above.
// This function will call itself several times if drilling into nested objects is required.
drillIntoObject(fieldsObject, fieldKey, objectNestLevel, "")
}
else // This top level field is not an object - It's just a regular field.
{
// Push the pathname to this top level field onto the array
keysOfFieldsArray.push(fieldKey);
}
} // End of: for (let fieldKey in fieldsObject){...}
// End of: // Loop thorough the top level fields
// Make a single object containing the key/value pairs found inside the defaultElements of each field.
let combinedDefaultElementsObject = {};
// There may be more than one default element for each field
// (Consider velocity calculated from both time and distance elements.)
// So loop through fieldsObject from the data dictionary and add key/value pairs
// found in the defaultElements object of each field object and add them to the
// combinedDefaultElementObject. What we are doing is copying defaultElements
// from different branches of the recordObject tree into one new object so that
// we can work with them.
// Loop thorough the top level fields
for (let fieldKey in fieldsObject)
{
// If this top level field is an object containing more fields inside...
if(fieldsObject[fieldKey][fieldKey + 0])
{
// Declare a function that we will use to drill into the object.
function drillIntoObject(address, objKey, previousPath, objectNestLevel)
{
// Check each property of the subobject to see if it too is an object.
for (let property in address[objKey][objKey + "0"])
{
// If the property is also an object then drill deeper.
if(address[objKey][objKey + "0"][property][property + "0"])
{
// This function calls itself so as to go deeper into the object.
drillIntoObject(address[objKey][objKey + "0"], property, previousPath + objKey + "_" + objKey + "0_", objectNestLevel + 1);
}
else // This property is not an object. We are at the end of the branch where we encounter a data field.
{
// Assemble the path through the current object to the current data field.
let objectPath = objKey + "_" + objKey + "0_" + property;
// If the current data field is nested then prepend the path to include the parent objects.
objectPath = previousPath.length === 0 ? objectPath : previousPath + objectPath;
// Grab all the defaultElements (form controls) for this data field.
// There may be several - Think time and distance controls required to calculate a velocity field
let defaultElementsObject = address[objKey][objKey + "0"][property].defaultElements;
// Loop through defaultElementsObject.
for (let elementKey in defaultElementsObject)
{
// Grab each defaultElement and copy to an object which will hold all defaultElements for the table.
combinedDefaultElementsObject[objectPath] = defaultElementsObject[elementKey];
}
} // End of: else - This property is not an object.
} // Check each property of the subobject to see if it too is an object.
}; // End of: function drillIntoObject(address, objKey, previousPath, objectNestLevel){...}
// Keep track of how deep we have drilled into the object.
let objectNestLevel = 1;
// Call the function defined above.
// This function will call itself several times if drilling into nested objects is required.
drillIntoObject(fieldsObject, fieldKey, "", objectNestLevel)
}
else // This top level field is not an object - It's just a regular data field.
{
// Create an object of default elements for the current data field.
let defaultElementsObject = fieldsObject[fieldKey].defaultElements;
// Loop through defaultElementsObject.
for (let elementKey in defaultElementsObject)
{
// Grab each defaultElement and copy to an object which will hold all defaultElements for this table.
combinedDefaultElementsObject[elementKey] = defaultElementsObject[elementKey];
}
}
} // End of: for (let fieldKey in fieldsObject){...}
// End of: // Loop thorough the top level fields
// Start of: Assemble the POST Handler
htmlString = htmlString +
`
// ${recordObject.tableName} - post subhandler
// Define the ${recordObject.tableName} post subhandler function.
// This function appends a record to the ${recordObject.tableName} file.
// Behavior from meta.js at 1723qxikk1l3ru0vfrny
${recordObject.tableName}._${recordObject.tableName}.post = function(data, callback)
{
// Field validation starts here.
`
let lastPart;
// Start of: Insert validation code for the post handler. ????
// 1. Loop through the combinedDefaultElementsObject.
for (let fieldKey in combinedDefaultElementsObject)
{
// console.log("2. This is combinedDefaultElementsObject[" + fieldKey + "]: " + "\n",combinedDefaultElementsObject[fieldKey], "\n\n");
// If there is a zero in the fieldKey then we are dealing with an object which contains fields inside.
if(fieldKey.includes("0"))
{
// Break up the fieldKey into an array split on the underscore.
let fieldKeyPartsArray = fieldKey.split("_");
// Get the last part of the fieldKey.
// That's everything after the last underscore.
// It's the fieldName without the object path.
lastPart = fieldKeyPartsArray[fieldKeyPartsArray.length - 1]
htmlString = htmlString +
`
// Start of: Load the ${lastPart}Array dynamically once the payload is known.
// Behavior from meta.js at lefq4oks90h34rvcw8sg
let ${lastPart}KeyArray = [`
// Loop through the *PartsArray adding any elements found to htmlString
// that do not have a zero.
fieldKeyPartsArray.forEach
(
function(currentPart, fieldKeyPartsArrayIndex, fieldKeyPartsArrayAsParam)
{
if(!currentPart.includes("0"))
{
htmlString = htmlString + "\"" + currentPart + "\"";
// Add a coma if we are not on the last element.
if(fieldKeyPartsArrayIndex < fieldKeyPartsArrayAsParam.length - 1)
{
htmlString = htmlString + ", ";
}
}
}
);
htmlString = htmlString +
`]
let ${lastPart}Array = loadPayloadArray(${lastPart}KeyArray, data.payload);
// End of: Load the ${lastPart}Array dynamically once the payload is known.
`
}
else // This is not a container object but rather a regular data field.
{
htmlString = htmlString +
" // Get " + fieldKey + " from payload" + "\n" +
" let " + fieldKey + " = data.payload[\"" + fieldKey + "\"];" + "\n" +
"\n";
}
// Merge the default validation objects with the post validation objects.
let mergedValidationObject = extend(true, combinedDefaultElementsObject[fieldKey].validation.default, combinedDefaultElementsObject[fieldKey].validation.post);
// console.log("3 The mergedValidationObject is:\n", mergedValidationObject, "\n")
// Loop through the validation property of each field.
for (let validationKey in mergedValidationObject)
{
// console.log("4. Below is the value of mergedValidationObject[" + validationKey + "] : \n" , mergedValidationObject[validationKey], "\n\n");
if(validationKey === "passIfString")
{
// If the user supplied the validation code
if(mergedValidationObject[validationKey])
{
htmlString = htmlString +
" // " + validationKey + "\n" +
" " + mergedValidationObject[validationKey] + "\n" +
"\n";
}
else // No user supplied validation. Create a generic validation code
{
// If there is a zero in the fieldKey then we are dealing with an object which contains fields inside.
if(fieldKey.includes("0"))
{
htmlString = htmlString +
`
// Start of: Validate elements in the ${lastPart}Array
// passIfString
// Behavior from meta.js at 7n1wj6bz5asgucz6nmkp
${lastPart}Array.forEach(function(arrayElement)
{
if(typeof(arrayElement[1]) != 'string'){return callback(400, {'Error' : '${lastPart} must be of datatype string'});}
});
// End of: Validate elements in the ${lastPart}Array
`
}
else // No zero in the fieldkey. This is a not a container object but rather a data field.
{
htmlString = htmlString +
" // passIfString Default behavior from meta.js at qif5xwvzgr7efln9xtr8" + "\n" +
" if(typeof(" + fieldKey + ") != 'string'){return callback(400, {'Error' : '" + fieldKey + " must be of datatype string'});}" + "\n" +
"\n";
}
} // End of: No user supplied validation. Create a generic validation code
} // End of: if(validationKey === "passIfString")
else if(validationKey === "passIfNotEmpty")
{
// If the user supplied the validation code
if(mergedValidationObject[validationKey])
{
htmlString = htmlString +
" // " + validationKey + "\n" +
" " + mergedValidationObject[validationKey] + "\n" +
"\n";
}
else // No user supplied validation. Create a generic validation code.
{
htmlString = htmlString +
" // passIfNotEmpty Default behavior from meta.js at eojwivwlhxkm1b837n2o" + "\n" +
" if(!" + fieldKey + " || " + fieldKey + ".trim().length === 0){return callback(400, {'Error' : 'No " + fieldKey + " was entered'});}else{" + fieldKey + " = " + fieldKey + ".trim()}" + "\n" +
"\n";
}
}
else if(validationKey === "passIfString&NotEmptyThenTrim")
{
// If the user supplied the validation code in the data dictionary
if(mergedValidationObject[validationKey])
{
htmlString = htmlString +
" // " + validationKey + "\n" +
" " + mergedValidationObject[validationKey] + "\n" +
"\n";
}
else // No user supplied validation code. Create a generic validation string.
{
// If there is a zero in the fieldKey then we are dealing with an object which contains fields inside.
if(fieldKey.includes("0"))
{
htmlString = htmlString +
`
// Start of: Validate elements in the ${lastPart}Array
// passIfString&NotEmptyThenTrim
// Behavior from meta.js at fkb3ulfqr09ryyc0rb0d
${lastPart}Array.forEach(function(arrayElement)
{
if(typeof(arrayElement[1]) != 'string'){return callback(400, {'Error' : '${lastPart} must be of datatype string'});}
if(!arrayElement[1] || arrayElement[1].trim().length === 0){return callback(400, {'Error' : 'No ${lastPart} was entered'});}else{arrayElement[1] = arrayElement[1].trim()}
});
// End of: Validate elements in the ${lastPart}Array
`
} // End of: If there is a zero in the fieldKey...
else // No zero in the fieldkey. This is a not a container object but rather a data field.
{
htmlString = htmlString +
` // passIfString&NotEmptyThenTrim Default behavior from meta.js at ulg5xxvzgr7efln9xur9
if(typeof(${fieldKey}) != 'string'){return callback(400, {'Error' : '${fieldKey} must be of datatype string'});}
if(!${fieldKey} || ${fieldKey}.trim().length === 0){return callback(400, {'Error' : 'No ${fieldKey} was entered'});}else{${fieldKey} = ${fieldKey}.trim()}
`
} // End of: Else: No zero in the fieldkey. This is a not a container object but rather a data field.
} // End of: // No user supplied validation code. Create a generic validation string.
} // End of: else if(validationKey === "passIfString&NotEmptyThenTrim")
else if(validationKey === "passMenuItemsOnly")
{
// If the user supplied the validation code in the data dictionary
if(mergedValidationObject[validationKey])
{
htmlString = htmlString +
" // " + validationKey + "\n" +
" " + mergedValidationObject[validationKey] + "\n" +
"\n";
}
else // No user supplied validation code. Create a generic validation string.
{
// If there is a zero in the fieldKey then we are dealing with an object which contains fields inside.
if(fieldKey.includes("0"))
{
htmlString = htmlString +
`
// Start of: Validate elements in the ${lastPart}Array
// passMenuItemsOnly
// Behavior from meta.js at 69nq4ck9lcdakwpb58o6
${lastPart}Array.forEach(function(arrayElement)
{
if(typeof(arrayElement[1]) != 'string')
{
return callback(400, {'Error' : '${lastPart} must be of datatype string'});
}
if
(
`
// Build validation for the menu options.
let isFirstOptionWrite = true;
Object.keys(combinedDefaultElementsObject[fieldKey].options).forEach
(
function(optionKey)
{
// If the option is not blank and this is the first option to be validated.
if(optionKey && isFirstOptionWrite)
{
htmlString = htmlString +
" arrayElement[1] !== \"" + optionKey + "\"" + "\n";
isFirstOptionWrite = false;
}
else if(optionKey)
{
htmlString = htmlString +
" && arrayElement[1] !== \"" + optionKey + "\"" + "\n";
}
}
);
htmlString = htmlString +
` )
{
return callback(400, {'Error' : '${lastPart} does not match menu options'});
}
});
// End of: Validate elements in the ${lastPart}Array
`
}
else // This is not a container object but rather just a regular data field.
{
htmlString = htmlString +
` // Behavior from meta.js at ettt3o23onrmd04b94jq
if(typeof(${fieldKey}) != 'string')
{
return callback(400, {'Error' : '${fieldKey} must be of datatype string'});
}
if
(
`
// Build validation for the menu options.
let isFirstOptionWrite = true;
Object.keys(combinedDefaultElementsObject[fieldKey].options).forEach
(
function(optionKey)
{
// If the option is not blank and this is the first option to be validated.
if(optionKey && isFirstOptionWrite)
{
htmlString = htmlString +
" " + fieldKey + " !== \"" + optionKey + "\"" + "\n";
isFirstOptionWrite = false;
}
else if(optionKey)
{
htmlString = htmlString +
" && " + fieldKey + " !== \"" + optionKey + "\"" + "\n";
}
}
);
htmlString = htmlString +
`
)
{
return callback(400, {'Error' : 'No ${fieldKey} was selected from menu'});
}
else
{
${fieldKey} = ${fieldKey}.trim()
}
`
} // End of: Else: This is not a container object but rather just a regular data field.
} // End of: Else: No user supplied validation code. Create a generic validation string.
} // End of: else if(validationKey === "passMenuItemsOnly"){...}
else // validationKey must be user defined.
{
// If the user supplied the validation string
if(mergedValidationObject[validationKey])
{
htmlString = htmlString +
" // " + validationKey + "\n" +
" " + mergedValidationObject[validationKey] + "\n" +
"\n";
}
}
} // End of: for for (let validationKey in mergedValidationObject){...}
} // End of: for (let fieldKey in combinedDefaultElementsObject)
// End of: Insert validation code.
// Start of Enforce unique fields.
// This code can only handle one uniqueId for each table for now.
// Later we will update this code to handle as many uniqueIds as may be required.
// Looks like we just need to put this section of code in a loop.
// Or better, Test for all the unique fields at the same time in a single loop.
// This code already handles the possibility that no fields are required to be unique.
// In that case the loop will not run and the following code will not be inserted.
// This causes the code that normally runs inside to be indented one tab too many.
// That can be fixed by running a beautifier on the code.
// I intend to build a simple beautifier into this generator but since this is only aesthetic it can wait.
// 1. Create an array with all the field names for fields which must be unique.
let uniqueFieldsArray = [];
// Loop thorough the top level fields drilling in as required.
for (let fieldKey in fieldsObject)
{
// If this top level field is an object containing more fields inside...
if(fieldsObject[fieldKey][fieldKey + "0"])
{
// Declare a function that we will use to drill into the object.
function drillIntoObject(address, objKey, previousObjKey, objectNestLevel)
{
// if the subfield is also an object then this function calls itself using the subfield parameters.
// This will continue drilling in until we are at the end of the branches.
if(address[objKey][objKey + "0"])
{
// Check each property of the subobject to see if it too is an object.
for (let property in address[objKey][objKey + "0"])
{
// If the property is also an object
if(address[objKey][objKey + "0"][property][property + "0"])
{
// This function calls itself so as to go deeper into the object
drillIntoObject(address[objKey][objKey + "0"], property, objKey, objectNestLevel + 1);
}
else // This property is not an object. We are at the end of the branch where we encounter a data field.
{
// Assemble the path through the current object to the current data field.
let objectPath = objKey + "." + objKey + "0." + property;
// If the current object is nested then prepend the path to include the parent objects.
objectPath = previousObjKey.length === 0 ? objectPath : previousObjKey + "." + objectPath;
// Check if the current field has a unique constraint.
if(address[objKey][objKey + "0"][property].unique === "yes")
{
uniqueFieldsArray.push(objectPath);
}
} // End of: else - This property is not an object.
} // End of: for-let Check each property of the subobject to see if it too is an object.
} // End of: if the subfield is also an object
}; // End of: function drillIntoObject(address, objKey, previousObjKey, previousKeyPart, objectNestLevel){...}
// Keep track of how deep we have drilled into the object.
let objectNestLevel = 1;
// Call the function defined above.
// This function will call itself several times if drilling into nested objects is required.
drillIntoObject(fieldsObject, fieldKey, "", objectNestLevel)
}
else // This top level field is not an object - It's just a regular data field.
{
if(fieldsObject[fieldKey].unique === "yes")
{
uniqueFieldsArray.push(fieldKey);
}
}
} // End of: for (let fieldKey in fieldsObject){...}
// End of: // Loop thorough the top level fields
// If there are unique key fields then insert code that checks uniqueness of the candidate value.
if(uniqueFieldsArray.length != 0)
{
let uniqueFieldInTitleCase = uniqueFieldsArray[0][0].toUpperCase() + uniqueFieldsArray[0].slice(1);
htmlString = htmlString +
`
// Enforcing uniqueness of the ${uniqueFieldsArray[0]} field.
// Will toggle this to false if we find the ${uniqueFieldsArray[0]} already exists in ${recordObject.tableName}.
// Behavior from meta.js at rmkfkaef7xo3gyvnvgm4
let ${uniqueFieldsArray[0].split(".").join("_")}_IsUnused = true;
// Using this to track the primary key of a record that we might encounter with the candidate ${uniqueFieldsArray[0]}.
// If we encounter this primary key again we will check to see if the ${uniqueFieldsArray[0]} has been changed.
// If it has then the candidate ${uniqueFieldsArray[0]} will be marked as available again.
let uniqueIdOfRecordHoldingCandidate_${uniqueFieldInTitleCase.split(".").join("_")} = false;
// To ensure the ${uniqueFieldsArray[0]} is unique we will read every record in
// ${recordObject.tableName} and compare with the ${uniqueFieldsArray[0]} provided.
// This function sets up a stream where each chunk of data is a complete line in the ${recordObject.tableName} file.
let readInterface = readline.createInterface
(
{ // specify the file to be read.
input: fs.createReadStream(_data.baseDir + '/${recordObject.directory}' + '/' + '${recordObject.tableName}' + '.json')
}
);
// Look at each record in the file and set a flag if the ${uniqueFieldsArray[0]} matches the ${uniqueFieldsArray[0]} provided by the user.
readInterface.on('line', function(line)
{
// Convert the JSON string from ${recordObject.tableName} into an object.
let lineObject = JSON.parse(line);
// Several different record sets with the supplied ${uniqueFieldsArray[0]} and the same ${recordObject.tableName}Id
// may exist already if the record has been changed or deleted prior to this operation.
// A modified record is simply a new record with the same ${recordObject.tableName}Id as an existing record.
// The newest record is the valid record and the older record is history.
// So position matters. These tables should never be sorted.
// These tables can be packed however to get rid of historical records.
// The transaction log also maintains the history and the current state of the entire database.
// So the transaction log can be used to check the integrity of the every table.
// No records in the transaction log should be removed.
// A deleted record in this system is simply an identical record appended with
// the deleted field set to true.
// So depending on how many times the ${uniqueFieldsArray[0]} has been added and deleted there may
// be several sets of records in the ${recordObject.tableName} table currently
// that have the same ${uniqueFieldsArray[0]} and the same ${recordObject.tableName}Id.
// The table can be packed occasionally to get rid of these deleted record sets.
// Deletes are handled as appends with the deleted field set to true because real
// deletes tie up the table for a long time.
// In this table, the ${uniqueFieldsArray[0]} is a unique key as well as the ${recordObject.tableName}Id.
// The ${recordObject.tableName}Id also serves as the primary key.
// The difference is that the ${recordObject.tableName}Id may never change whereas the ${uniqueFieldsArray[0]}
// may be changed to something different if a valid record for that ${uniqueFieldsArray[0]}
// does not already exist.