@carbonorm/carbonnode 3.0.1 → 3.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -339,6 +339,15 @@ function restRequest(config) {
339
339
  };
340
340
  }
341
341
 
342
+ function restOrm(config) {
343
+ return {
344
+ Get: restRequest(__assign(__assign({}, config), { requestMethod: "GET" })),
345
+ Put: restRequest(__assign(__assign({}, config), { requestMethod: "PUT" })),
346
+ Post: restRequest(__assign(__assign({}, config), { requestMethod: "POST" })),
347
+ Delete: restRequest(__assign(__assign({}, config), { requestMethod: "DELETE" })),
348
+ };
349
+ }
350
+
342
351
  function timeout(shouldContinueAfterTimeout, cb, timeoutMs) {
343
352
  if (timeoutMs === void 0) { timeoutMs = 3000; }
344
353
  var timer = function () { return setTimeout(function () {
@@ -512,15 +521,6 @@ function buildSelectQuery(table, primary, args, isSubSelect) {
512
521
  return sql;
513
522
  }
514
523
 
515
- var Executor = /** @class */ (function () {
516
- function Executor(config, request) {
517
- if (request === void 0) { request = {}; }
518
- this.config = config;
519
- this.request = request;
520
- }
521
- return Executor;
522
- }());
523
-
524
524
  function getEnvVar(key, fallback) {
525
525
  if (fallback === void 0) { fallback = ''; }
526
526
  // Vite-style injection
@@ -536,15 +536,68 @@ function getEnvVar(key, fallback) {
536
536
  return fallback;
537
537
  }
538
538
 
539
+ var envVerbose = getEnvVar('VERBOSE') || getEnvVar('REACT_APP_VERBOSE') || getEnvVar('VITE_VERBOSE') || '';
540
+ var isVerbose = ['true', '1', 'yes', 'on'].includes(envVerbose.toLowerCase());
541
+
542
+ var Executor = /** @class */ (function () {
543
+ function Executor(config, request) {
544
+ if (request === void 0) { request = {}; }
545
+ this.config = config;
546
+ this.request = request;
547
+ }
548
+ Executor.prototype.runLifecycleHooks = function (phase, args) {
549
+ return __awaiter(this, void 0, void 0, function () {
550
+ var lifecycleGroup, _i, _a, _b, key, fn, err_1;
551
+ var _c;
552
+ return __generator(this, function (_d) {
553
+ switch (_d.label) {
554
+ case 0:
555
+ lifecycleGroup = (_c = this.config.restModel.LIFECYCLE_HOOKS[this.config.requestMethod]) === null || _c === void 0 ? void 0 : _c[phase];
556
+ if (!lifecycleGroup)
557
+ return [2 /*return*/];
558
+ _i = 0, _a = Object.entries(lifecycleGroup);
559
+ _d.label = 1;
560
+ case 1:
561
+ if (!(_i < _a.length)) return [3 /*break*/, 6];
562
+ _b = _a[_i], key = _b[0], fn = _b[1];
563
+ if (!(typeof fn === "function")) return [3 /*break*/, 5];
564
+ if (isVerbose || args.request.debug) {
565
+ console.groupCollapsed("[LIFECYCLE] ".concat(this.config.requestMethod, ".").concat(String(phase), ":").concat(key));
566
+ console.log("config:", args.config);
567
+ console.log("request:", args.request);
568
+ if ("response" in args) {
569
+ console.log("response:", args.response);
570
+ }
571
+ console.groupEnd();
572
+ }
573
+ _d.label = 2;
574
+ case 2:
575
+ _d.trys.push([2, 4, , 5]);
576
+ return [4 /*yield*/, fn(args)];
577
+ case 3:
578
+ _d.sent();
579
+ return [3 /*break*/, 5];
580
+ case 4:
581
+ err_1 = _d.sent();
582
+ console.error("[LIFECYCLE ERROR] ".concat(this.config.requestMethod, ".").concat(String(phase), ":").concat(key), err_1);
583
+ throw err_1;
584
+ case 5:
585
+ _i++;
586
+ return [3 /*break*/, 1];
587
+ case 6: return [2 /*return*/];
588
+ }
589
+ });
590
+ });
591
+ };
592
+ return Executor;
593
+ }());
594
+
539
595
  var isDevelopment = getEnvVar('NODE_ENV', '') === 'development';
540
596
 
541
597
  var isTest = getEnvVar('JEST_WORKER_ID') || getEnvVar('NODE_ENV') === 'test'
542
598
  || getEnvVar('REACT_APP_TEST') === 'true' || getEnvVar('VITE_TEST') === 'true'
543
599
  || getEnvVar('MODE') === 'test' || getEnvVar('VITE_TEST_MODE') === 'true';
544
600
 
545
- var envVerbose = getEnvVar('VERBOSE') || getEnvVar('REACT_APP_VERBOSE') || getEnvVar('VITE_VERBOSE') || '';
546
- var isVerbose = ['true', '1', 'yes', 'on'].includes(envVerbose.toLowerCase());
547
-
548
601
  var eFetchDependencies;
549
602
  (function (eFetchDependencies) {
550
603
  eFetchDependencies[eFetchDependencies["NONE"] = 0] = "NONE";
@@ -574,9 +627,6 @@ var DELETE = 'DELETE';
574
627
  function isPromise(x) {
575
628
  return Object(x).constructor === Promise;
576
629
  }
577
- function extendedTypeHints() {
578
- return function (argv) { return restRequest(argv); };
579
- }
580
630
 
581
631
  var toastOptions = {
582
632
  position: "bottom-left",
@@ -688,17 +738,71 @@ var HttpExecutor = /** @class */ (function (_super) {
688
738
  function HttpExecutor() {
689
739
  return _super !== null && _super.apply(this, arguments) || this;
690
740
  }
741
+ HttpExecutor.prototype.putState = function (response, request, callback) {
742
+ var _a, _b;
743
+ (_a = this.config.reactBootstrap) === null || _a === void 0 ? void 0 : _a.updateRestfulObjectArrays({
744
+ callback: callback,
745
+ dataOrCallback: [
746
+ removeInvalidKeys(__assign(__assign({}, request), (_b = response === null || response === void 0 ? void 0 : response.data) === null || _b === void 0 ? void 0 : _b.rest), this.config.C6.TABLES)
747
+ ],
748
+ stateKey: this.config.restModel.TABLE_NAME,
749
+ uniqueObjectId: this.config.restModel.PRIMARY_SHORT
750
+ });
751
+ };
752
+ HttpExecutor.prototype.postState = function (response, request, callback) {
753
+ var _this = this;
754
+ var _a, _b, _c;
755
+ if (1 !== this.config.restModel.PRIMARY_SHORT.length) {
756
+ console.error("C6 received unexpected result's given the primary key length");
757
+ }
758
+ else {
759
+ var pk = this.config.restModel.PRIMARY_SHORT[0];
760
+ // TODO - should overrides be handled differently? Why override: (react/php), driver missmatches, aux data..
761
+ // @ts-ignore - this is technically a correct error, but we allow it anyway...
762
+ request[pk] = (_a = response.data) === null || _a === void 0 ? void 0 : _a.created;
763
+ }
764
+ (_b = this.config.reactBootstrap) === null || _b === void 0 ? void 0 : _b.updateRestfulObjectArrays({
765
+ callback: callback,
766
+ dataOrCallback: undefined !== request.dataInsertMultipleRows
767
+ ? request.dataInsertMultipleRows.map(function (request, index) {
768
+ var _a;
769
+ return removeInvalidKeys(__assign(__assign({}, request), (index === 0 ? (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.rest : {})), _this.config.C6.TABLES);
770
+ })
771
+ : [
772
+ removeInvalidKeys(__assign(__assign({}, request), (_c = response === null || response === void 0 ? void 0 : response.data) === null || _c === void 0 ? void 0 : _c.rest), this.config.C6.TABLES)
773
+ ],
774
+ stateKey: this.config.restModel.TABLE_NAME,
775
+ uniqueObjectId: this.config.restModel.PRIMARY_SHORT
776
+ });
777
+ };
778
+ HttpExecutor.prototype.deleteState = function (_response, request, callback) {
779
+ var _a;
780
+ (_a = this.config.reactBootstrap) === null || _a === void 0 ? void 0 : _a.deleteRestfulObjectArrays({
781
+ callback: callback,
782
+ dataOrCallback: [
783
+ request,
784
+ ],
785
+ stateKey: this.config.restModel.TABLE_NAME,
786
+ uniqueObjectId: this.config.restModel.PRIMARY_SHORT
787
+ });
788
+ };
691
789
  HttpExecutor.prototype.execute = function () {
692
790
  return __awaiter(this, void 0, void 0, function () {
693
- var _a, C6, axios, restURL, withCredentials, tableName, requestMethod, queryCallback, responseCallback, skipPrimaryCheck, clearCache, fullTableList, operatingTableFullName, operatingTable, tables, query, apiRequest;
694
- var _this = this;
791
+ var _a, C6, restModel, requestMethod, clearCache, tableName, fullTableList, operatingTableFullName, tables;
695
792
  return __generator(this, function (_b) {
696
793
  switch (_b.label) {
697
794
  case 0:
698
- _a = this.config, C6 = _a.C6, axios = _a.axios, restURL = _a.restURL, withCredentials = _a.withCredentials, tableName = _a.tableName, requestMethod = _a.requestMethod, queryCallback = _a.queryCallback, responseCallback = _a.responseCallback, skipPrimaryCheck = _a.skipPrimaryCheck, clearCache = _a.clearCache;
795
+ _a = this.config, C6 = _a.C6, _a.axios, _a.restURL, _a.withCredentials, restModel = _a.restModel, _a.reactBootstrap, requestMethod = _a.requestMethod, _a.skipPrimaryCheck, clearCache = _a.clearCache;
796
+ return [4 /*yield*/, this.runLifecycleHooks("beforeProcessing", {
797
+ config: this.config,
798
+ request: this.request,
799
+ })];
800
+ case 1:
801
+ _b.sent();
802
+ tableName = restModel.TABLE_NAME;
699
803
  fullTableList = Array.isArray(tableName) ? tableName : [tableName];
700
804
  operatingTableFullName = fullTableList[0];
701
- operatingTable = removePrefixIfExists(operatingTableFullName, C6.PREFIX);
805
+ removePrefixIfExists(operatingTableFullName, C6.PREFIX);
702
806
  tables = fullTableList.join(',');
703
807
  switch (requestMethod) {
704
808
  case GET:
@@ -715,13 +819,7 @@ var HttpExecutor = /** @class */ (function (_super) {
715
819
  console.groupCollapsed('%c API: (' + requestMethod + ') Request for (' + tableName + ')', 'color: #0c0');
716
820
  console.log('request', this.request);
717
821
  console.groupEnd();
718
- if ('function' === typeof queryCallback) {
719
- query = queryCallback(this.request); // obj or obj[]
720
- }
721
- else {
722
- query = queryCallback;
723
- }
724
- if (undefined === query || null === query) {
822
+ {
725
823
  if (this.request.debug && isDevelopment) {
726
824
  toast.warning("DEV: queryCallback returned undefined, signaling in Custom Cache. (returning null)", toastOptionsDevs);
727
825
  }
@@ -731,456 +829,7 @@ var HttpExecutor = /** @class */ (function (_super) {
731
829
  console.groupEnd();
732
830
  return [2 /*return*/, null];
733
831
  }
734
- if (C6.GET === requestMethod) {
735
- if (undefined === query[C6.PAGINATION]) {
736
- query[C6.PAGINATION] = {};
737
- }
738
- query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
739
- query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
740
- }
741
- apiRequest = function () { return __awaiter(_this, void 0, void 0, function () {
742
- var _a, debug, _b, cacheResults, dataInsertMultipleRows, success, _c, fetchDependencies, _d, error, querySerialized, cacheResult, cachingConfirmed, cacheCheck, cacheCheck, addBackPK, apiResponse, returnGetNextPageFunction, restRequestUri, needsConditionOrPrimaryCheck, TABLES, primaryKey, removedPkValue_1, axiosActiveRequest;
743
- var _e;
744
- var _this = this;
745
- var _f, _g, _h, _j, _k, _l;
746
- return __generator(this, function (_m) {
747
- _a = this.request, debug = _a.debug, _b = _a.cacheResults, cacheResults = _b === void 0 ? (C6.GET === requestMethod) : _b, dataInsertMultipleRows = _a.dataInsertMultipleRows, success = _a.success, _c = _a.fetchDependencies, fetchDependencies = _c === void 0 ? eFetchDependencies.NONE : _c, _d = _a.error, error = _d === void 0 ? "An unexpected API error occurred!" : _d;
748
- if (C6.GET === requestMethod
749
- && undefined !== ((_f = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _f === void 0 ? void 0 : _f[C6.PAGE])
750
- && 1 !== query[C6.PAGINATION][C6.PAGE]) {
751
- console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
752
- console.log('Request Data (note you may see the success and/or error prompt):', this.request);
753
- console.trace();
754
- console.groupEnd();
755
- }
756
- querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
757
- cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
758
- cachingConfirmed = false;
759
- // determine if we need to paginate.
760
- if (requestMethod === C6.GET) {
761
- if (undefined === (query === null || query === void 0 ? void 0 : query[C6.PAGINATION])) {
762
- if (undefined === query || null === query) {
763
- query = {};
764
- }
765
- query[C6.PAGINATION] = {};
766
- }
767
- query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
768
- query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
769
- // this will evaluate true most the time
770
- if (true === cacheResults) {
771
- // just find the next, non-fetched, page and return a function to request it
772
- if (undefined !== cacheResult) {
773
- do {
774
- cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
775
- if (false !== cacheCheck) {
776
- return [2 /*return*/, cacheCheck];
777
- }
778
- // this line incrementing page is why we return recursively
779
- ++query[C6.PAGINATION][C6.PAGE];
780
- // this json stringify is to capture the new page number
781
- querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
782
- cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
783
- } while (undefined !== cacheResult);
784
- if (debug && isDevelopment) {
785
- toast.warning("DEVS: Request in cache. (" + apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; }) + "). Returning function to request page (" + query[C6.PAGINATION][C6.PAGE] + ")", toastOptionsDevs);
786
- }
787
- // @ts-ignore - this is an incorrect warning on TS, it's well typed
788
- return [2 /*return*/, apiRequest];
789
- }
790
- cachingConfirmed = true;
791
- }
792
- else {
793
- if (debug && isDevelopment) {
794
- toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
795
- }
796
- }
797
- if (debug && isDevelopment) {
798
- toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
799
- }
800
- }
801
- else if (cacheResults) { // if we are not getting, we are updating, deleting, or inserting
802
- if (cacheResult) {
803
- cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
804
- if (false !== cacheCheck) {
805
- return [2 /*return*/, cacheCheck];
806
- }
807
- }
808
- cachingConfirmed = true;
809
- // push to cache so we do not repeat the request
810
- }
811
- returnGetNextPageFunction = false;
812
- restRequestUri = restURL + operatingTable + '/';
813
- needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
814
- && false === skipPrimaryCheck;
815
- TABLES = C6.TABLES;
816
- primaryKey = (_k = (_j = (_h = structuredClone((_g = TABLES[operatingTable]) === null || _g === void 0 ? void 0 : _g.PRIMARY)) === null || _h === void 0 ? void 0 : _h.pop()) === null || _j === void 0 ? void 0 : _j.split('.')) === null || _k === void 0 ? void 0 : _k.pop();
817
- if (needsConditionOrPrimaryCheck) {
818
- if (undefined === primaryKey) {
819
- if (null === query
820
- || undefined === query
821
- || undefined === (query === null || query === void 0 ? void 0 : query[C6.WHERE])
822
- || (true === Array.isArray(query[C6.WHERE])
823
- || query[C6.WHERE].length === 0)
824
- || (Object.keys(query === null || query === void 0 ? void 0 : query[C6.WHERE]).length === 0)) {
825
- console.error(query);
826
- throw Error('Failed to parse primary key information. Query: (' + JSON.stringify(query) + ') Primary Key: (' + JSON.stringify(primaryKey) + ') TABLES[operatingTable]?.PRIMARY: (' + JSON.stringify((_l = TABLES[operatingTable]) === null || _l === void 0 ? void 0 : _l.PRIMARY) + ') for operatingTable (' + operatingTable + ').');
827
- }
828
- }
829
- else {
830
- if (undefined === query
831
- || null === query
832
- || false === primaryKey in query) {
833
- if (true === debug && isDevelopment) {
834
- toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
835
- }
836
- throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(this.request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
837
- }
838
- if (undefined === (query === null || query === void 0 ? void 0 : query[primaryKey])
839
- || null === (query === null || query === void 0 ? void 0 : query[primaryKey])) {
840
- toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!');
841
- throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
842
- }
843
- }
844
- }
845
- // A part of me exists that wants to remove this, but it's a good feature
846
- // this allows developers the ability to cache requests based on primary key
847
- // for tables like `photos` this can be a huge performance boost
848
- if (undefined !== query
849
- && null !== query
850
- && undefined !== primaryKey
851
- && primaryKey in query) {
852
- restRequestUri += query[primaryKey] + '/';
853
- removedPkValue_1 = query[primaryKey];
854
- addBackPK = function () {
855
- query !== null && query !== void 0 ? query : (query = {});
856
- query[primaryKey] = removedPkValue_1;
857
- };
858
- delete query[primaryKey];
859
- console.log('query', query, 'primaryKey', primaryKey, 'removedPkValue', removedPkValue_1);
860
- }
861
- else {
862
- console.log('query', query);
863
- }
864
- try {
865
- console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
866
- console.log(this.request);
867
- console.log('%c If this is the first request for this datatype; thus the value being set is currently undefined, please remember to update the state to null.', 'color: #A020F0');
868
- console.log('%c Remember undefined indicated the request has not fired, null indicates the request is firing, an empty array would signal no data was returned for the sql stmt.', 'color: #A020F0');
869
- console.trace();
870
- console.groupEnd();
871
- axiosActiveRequest = (_e = axios)[requestMethod.toLowerCase()].apply(_e, __spreadArray([restRequestUri], ((function () {
872
- // @link - https://axios-http.com/docs/instance
873
- // How configuration vs data is passed is variable, use documentation above for reference
874
- if (requestMethod === GET) {
875
- return [{
876
- withCredentials: withCredentials,
877
- params: query
878
- }];
879
- }
880
- else if (requestMethod === POST) {
881
- if (undefined !== dataInsertMultipleRows) {
882
- return [
883
- dataInsertMultipleRows.map(function (data) {
884
- return convertForRequestBody(data, fullTableList, C6, function (message) { return toast.error(message, toastOptions); });
885
- }),
886
- {
887
- withCredentials: withCredentials,
888
- }
889
- ];
890
- }
891
- return [
892
- convertForRequestBody(query, fullTableList, C6, function (message) { return toast.error(message, toastOptions); }),
893
- {
894
- withCredentials: withCredentials,
895
- }
896
- ];
897
- }
898
- else if (requestMethod === PUT) {
899
- return [
900
- convertForRequestBody(query, fullTableList, C6, function (message) { return toast.error(message, toastOptions); }),
901
- {
902
- withCredentials: withCredentials,
903
- }
904
- ];
905
- }
906
- else if (requestMethod === DELETE) {
907
- return [{
908
- withCredentials: withCredentials,
909
- data: convertForRequestBody(query, fullTableList, C6, function (message) { return toast.error(message, toastOptions); })
910
- }];
911
- }
912
- else {
913
- throw new Error('The request method (' + requestMethod + ') was not recognized.');
914
- }
915
- })()), false));
916
- if (cachingConfirmed) {
917
- // push to cache so we do not repeat the request
918
- apiRequestCache.push({
919
- requestArgumentsSerialized: querySerialized,
920
- request: axiosActiveRequest
921
- });
922
- }
923
- // todo - wip verify this works
924
- // we had removed the value from the request to add to the URI.
925
- addBackPK === null || addBackPK === void 0 ? void 0 : addBackPK(); // adding back so post-processing methods work
926
- // returning the promise with this then is important for tests. todo - we could make that optional.
927
- // https://rapidapi.com/guides/axios-async-await
928
- return [2 /*return*/, axiosActiveRequest.then(function (response) { return __awaiter(_this, void 0, void 0, function () {
929
- var cacheIndex, responseData_1, dependencies_1, fetchReferences_1, apiRequestPromises, _loop_1, _a, _b, _c, _i, tableToFetch;
930
- var _this = this;
931
- var _d, _e, _f, _g, _h, _j, _k;
932
- return __generator(this, function (_l) {
933
- switch (_l.label) {
934
- case 0:
935
- if (typeof response.data === 'string') {
936
- if (isTest) {
937
- console.trace();
938
- throw new Error('The response data was a string this typically indicated html was sent. Make sure all cookies (' + JSON.stringify(response.config.headers) + ') needed are present! (' + response.data + ')');
939
- }
940
- return [2 /*return*/, Promise.reject(response)];
941
- }
942
- if (cachingConfirmed) {
943
- cacheIndex = apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
944
- apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction;
945
- // only cache get method requests
946
- apiRequestCache[cacheIndex].response = response;
947
- }
948
- apiResponse = TestRestfulResponse(response, success, error);
949
- if (false === apiResponse) {
950
- if (debug && isDevelopment) {
951
- toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
952
- }
953
- return [2 /*return*/, response];
954
- }
955
- // stateful operations are done in the response callback - its leverages rest generated functions
956
- if (responseCallback) {
957
- responseCallback(response, this.request, apiResponse);
958
- }
959
- if (!(C6.GET === requestMethod)) return [3 /*break*/, 6];
960
- responseData_1 = response.data;
961
- returnGetNextPageFunction = 1 !== ((_d = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _d === void 0 ? void 0 : _d[C6.LIMIT]) &&
962
- ((_e = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _e === void 0 ? void 0 : _e[C6.LIMIT]) === responseData_1.rest.length;
963
- if (false === isTest || true === isVerbose) {
964
- console.groupCollapsed('%c API: Response (' + requestMethod + ' ' + tableName + ') returned length (' + ((_f = responseData_1.rest) === null || _f === void 0 ? void 0 : _f.length) + ') of possible (' + ((_g = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _g === void 0 ? void 0 : _g[C6.LIMIT]) + ') limit!', 'color: #0c0');
965
- console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
966
- console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', this.request);
967
- console.log('%c Response Data:', 'color: #0c0', responseData_1.rest);
968
- console.log('%c Will return get next page function:' + (1 !== ((_h = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _h === void 0 ? void 0 : _h[C6.LIMIT]) ? '' : ' (Will not return with explicit limit 1 set)'), 'color: #0c0', true === returnGetNextPageFunction);
969
- console.trace();
970
- console.groupEnd();
971
- }
972
- if (false === returnGetNextPageFunction
973
- && true === debug
974
- && isDevelopment) {
975
- toast.success("DEVS: Response returned length (" + ((_j = responseData_1.rest) === null || _j === void 0 ? void 0 : _j.length) + ") less than limit (" + ((_k = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _k === void 0 ? void 0 : _k[C6.LIMIT]) + ").", toastOptionsDevs);
976
- }
977
- if (!(fetchDependencies
978
- && 'number' === typeof fetchDependencies
979
- && responseData_1.rest.length > 0)) return [3 /*break*/, 6];
980
- console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
981
- + (fetchDependencies & eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
982
- + (fetchDependencies & eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
983
- + (fetchDependencies & eFetchDependencies.C6ENTITY ? ' | (C6ENTITY)' : '')
984
- + (fetchDependencies & eFetchDependencies.RECURSIVE ? ' | (RECURSIVE)' : ''), 'color: #33ccff');
985
- console.groupCollapsed('Collapsed JS Trace');
986
- console.trace(); // hidden in collapsed group
987
- console.groupEnd();
988
- dependencies_1 = {};
989
- if (fetchDependencies & eFetchDependencies.C6ENTITY) {
990
- dependencies_1 = operatingTable.endsWith("carbon_carbons")
991
- ? __assign(__assign({}, fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
992
- ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
993
- : {}), fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
994
- ? C6.TABLES[operatingTable].TABLE_REFERENCES
995
- : {}) : __assign(__assign({}, fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
996
- ? __assign(__assign({}, Object.keys(C6.TABLES[operatingTable].TABLE_REFERENCES).reduce(function (accumulator, columnName) {
997
- if (!C6.TABLES[operatingTable].PRIMARY_SHORT.includes(columnName)) {
998
- accumulator[columnName] = C6.TABLES[operatingTable].TABLE_REFERENCES[columnName];
999
- }
1000
- return accumulator;
1001
- }, {})), C6.TABLES[operatingTable].TABLE_REFERENCED_BY // it is unlikely that a C6 table will have any TABLE_REFERENCED_BY
1002
- ) : {}), fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
1003
- ? C6.TABLES[operatingTable].PRIMARY_SHORT.reduce(function (accumulator, primaryKey) {
1004
- if (primaryKey in C6.TABLES[operatingTable].TABLE_REFERENCES) {
1005
- accumulator[primaryKey] = C6.TABLES[operatingTable].TABLE_REFERENCES[primaryKey];
1006
- }
1007
- return accumulator;
1008
- }, {})
1009
- : {});
1010
- }
1011
- else {
1012
- // this is the natural mysql context
1013
- dependencies_1 = __assign(__assign({}, fetchDependencies & eFetchDependencies.REFERENCED // REFERENCED === CHILDREN
1014
- ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1015
- : {}), fetchDependencies & eFetchDependencies.REFERENCES // REFERENCES === PARENTS
1016
- ? C6.TABLES[operatingTable].TABLE_REFERENCES
1017
- : {});
1018
- }
1019
- fetchReferences_1 = {};
1020
- apiRequestPromises = [];
1021
- console.log('%c Dependencies', 'color: #005555', dependencies_1);
1022
- Object.keys(dependencies_1)
1023
- .forEach(function (column) { return dependencies_1[column]
1024
- .forEach(function (constraint) {
1025
- var _a, _b, _c, _d;
1026
- var _e, _f, _g;
1027
- var columnValues = (_b = (_a = responseData_1.rest[column]) !== null && _a !== void 0 ? _a : responseData_1.rest.map(function (row) {
1028
- if (operatingTable.endsWith("carbons")
1029
- && 'entity_tag' in row
1030
- && !constraint.TABLE.endsWith(row['entity_tag'].split('\\').pop().toLowerCase())) {
1031
- return false; // map
1032
- }
1033
- if (!(column in row)) {
1034
- return false;
1035
- }
1036
- // todo - row[column] is a FK value, we should optionally remove values that are already in state
1037
- // this could be any column in the table constraint.TABLE, not just the primary key
1038
- return row[column];
1039
- }).filter(function (n) { return n; })) !== null && _b !== void 0 ? _b : [];
1040
- if (columnValues.length === 0) {
1041
- return; // forEach
1042
- }
1043
- (_c = fetchReferences_1[_e = constraint.TABLE]) !== null && _c !== void 0 ? _c : (fetchReferences_1[_e] = {});
1044
- (_d = (_f = fetchReferences_1[constraint.TABLE])[_g = constraint.COLUMN]) !== null && _d !== void 0 ? _d : (_f[_g] = []);
1045
- fetchReferences_1[constraint.TABLE][constraint.COLUMN].push(columnValues);
1046
- }); });
1047
- console.log('fetchReferences', fetchReferences_1);
1048
- _loop_1 = function (tableToFetch) {
1049
- var referencesTables, shouldContinue, fetchTable, RestApi, nextFetchDependencies;
1050
- var _m;
1051
- return __generator(this, function (_o) {
1052
- switch (_o.label) {
1053
- case 0:
1054
- if (fetchDependencies & eFetchDependencies.C6ENTITY
1055
- && 'string' === typeof tableName
1056
- && tableName.endsWith("carbon_carbons")) {
1057
- referencesTables = responseData_1.rest.reduce(function (accumulator, row) {
1058
- if ('entity_tag' in row && !accumulator.includes(row['entity_tag'])) {
1059
- accumulator.push(row['entity_tag']);
1060
- }
1061
- return accumulator;
1062
- }, []).map(function (entityTag) { return entityTag.split('\\').pop().toLowerCase(); });
1063
- shouldContinue = referencesTables.find(function (referencesTable) { return tableToFetch.endsWith(referencesTable); });
1064
- if (!shouldContinue) {
1065
- console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables);
1066
- return [2 /*return*/, "continue"];
1067
- }
1068
- console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') will be fetched.', 'color: #0c0');
1069
- }
1070
- return [4 /*yield*/, C6.IMPORT(tableToFetch)];
1071
- case 1:
1072
- fetchTable = _o.sent();
1073
- RestApi = fetchTable.default;
1074
- console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff');
1075
- nextFetchDependencies = eFetchDependencies.NONE;
1076
- if (fetchDependencies & eFetchDependencies.RECURSIVE) {
1077
- if (fetchDependencies & eFetchDependencies.ALL) {
1078
- throw Error('Recursive fetch dependencies with both PARENT and CHILD reference will result in an infin1ite loop. As there is not real ending condition, this is not supported.');
1079
- }
1080
- nextFetchDependencies = fetchDependencies;
1081
- }
1082
- else if (fetchDependencies & eFetchDependencies.C6ENTITY) {
1083
- if (tableToFetch === "carbon_carbons") {
1084
- nextFetchDependencies = fetchDependencies;
1085
- }
1086
- else {
1087
- nextFetchDependencies = fetchDependencies ^ eFetchDependencies.C6ENTITY;
1088
- }
1089
- }
1090
- console.log('fetchReferences', fetchReferences_1[tableToFetch], "Current fetchDependencies for (" + operatingTable + "):", fetchDependencies, "New fetchDependencies for (" + tableToFetch + "): ", nextFetchDependencies);
1091
- // todo - filter out ids that exist in state?!? note - remember that this does not necessarily mean the pk, but only known is its an FK to somewhere
1092
- // it not certain that they are using carbons' entities either
1093
- // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
1094
- // todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
1095
- apiRequestPromises.push(RestApi.Get((_m = {},
1096
- _m[C6.WHERE] = {
1097
- 0: Object.keys(fetchReferences_1[tableToFetch]).reduce(function (sum, column) {
1098
- fetchReferences_1[tableToFetch][column] = fetchReferences_1[tableToFetch][column].flat(Infinity);
1099
- if (0 === fetchReferences_1[tableToFetch][column].length) {
1100
- console.warn('The column (' + column + ') was not found in the response data. We will not fetch.', responseData_1);
1101
- return false;
1102
- }
1103
- sum[column] = fetchReferences_1[tableToFetch][column].length === 1
1104
- ? fetchReferences_1[tableToFetch][column][0]
1105
- : [
1106
- C6.IN, fetchReferences_1[tableToFetch][column]
1107
- ];
1108
- return sum;
1109
- }, {})
1110
- },
1111
- _m.fetchDependencies = nextFetchDependencies,
1112
- _m)));
1113
- return [2 /*return*/];
1114
- }
1115
- });
1116
- };
1117
- _a = fetchReferences_1;
1118
- _b = [];
1119
- for (_c in _a)
1120
- _b.push(_c);
1121
- _i = 0;
1122
- _l.label = 1;
1123
- case 1:
1124
- if (!(_i < _b.length)) return [3 /*break*/, 4];
1125
- _c = _b[_i];
1126
- if (!(_c in _a)) return [3 /*break*/, 3];
1127
- tableToFetch = _c;
1128
- return [5 /*yield**/, _loop_1(tableToFetch)];
1129
- case 2:
1130
- _l.sent();
1131
- _l.label = 3;
1132
- case 3:
1133
- _i++;
1134
- return [3 /*break*/, 1];
1135
- case 4:
1136
- console.groupEnd();
1137
- return [4 /*yield*/, Promise.all(apiRequestPromises)];
1138
- case 5:
1139
- _l.sent();
1140
- apiRequestPromises.map(function (promise) { return __awaiter(_this, void 0, void 0, function () {
1141
- var _a, _b;
1142
- return __generator(this, function (_c) {
1143
- switch (_c.label) {
1144
- case 0:
1145
- if (!Array.isArray(this.request.fetchDependencies)) {
1146
- // to reassign value we must ref the root
1147
- this.request.fetchDependencies = [];
1148
- }
1149
- _b = (_a = this.request.fetchDependencies).push;
1150
- return [4 /*yield*/, promise];
1151
- case 1:
1152
- _b.apply(_a, [_c.sent()]);
1153
- return [2 /*return*/];
1154
- }
1155
- });
1156
- }); });
1157
- _l.label = 6;
1158
- case 6:
1159
- if (debug && isDevelopment) {
1160
- toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1161
- }
1162
- return [2 /*return*/, response];
1163
- }
1164
- });
1165
- }); })];
1166
- }
1167
- catch (throwableError) {
1168
- if (isTest) {
1169
- throw new Error(JSON.stringify(throwableError));
1170
- }
1171
- console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
1172
- console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
1173
- console.warn(throwableError);
1174
- console.trace();
1175
- console.groupEnd();
1176
- TestRestfulResponse(throwableError, success, error);
1177
- return [2 /*return*/, null];
1178
- }
1179
- return [2 /*return*/];
1180
- });
1181
- }); };
1182
- return [4 /*yield*/, apiRequest()];
1183
- case 1: return [2 /*return*/, _b.sent()];
832
+ case 2: return [2 /*return*/, _b.sent()];
1184
833
  }
1185
834
  });
1186
835
  });
@@ -1201,13 +850,13 @@ var SqlExecutor = /** @class */ (function (_super) {
1201
850
  SqlExecutor.prototype.execute = function () {
1202
851
  switch (this.config.requestMethod) {
1203
852
  case 'GET':
1204
- return this.select(this.config.tableName, undefined, this.request).then(function (rows) { return ({ rest: rows }); });
853
+ return this.select(this.config.restModel.TABLE_NAME, undefined, this.request).then(function (rows) { return ({ rest: rows }); });
1205
854
  case 'POST':
1206
- return this.insert(this.config.tableName, this.request);
855
+ return this.insert(this.config.restModel.TABLE_NAME, this.request);
1207
856
  case 'PUT':
1208
- return this.update(this.config.tableName, undefined, this.request);
857
+ return this.update(this.config.restModel.TABLE_NAME, undefined, this.request);
1209
858
  case 'DELETE':
1210
- return this.delete(this.config.tableName, undefined, this.request);
859
+ return this.delete(this.config.restModel.TABLE_NAME, undefined, this.request);
1211
860
  }
1212
861
  };
1213
862
  SqlExecutor.prototype.withConnection = function (cb) {
@@ -1350,6 +999,49 @@ var SqlExecutor$1 = /*#__PURE__*/Object.freeze({
1350
999
  SqlExecutor: SqlExecutor
1351
1000
  });
1352
1001
 
1002
+ function determineRuntimeJsType(mysqlType) {
1003
+ var base = mysqlType.toLowerCase().split('(')[0];
1004
+ if ([
1005
+ 'binary', 'varbinary', 'blob', 'tinyblob', 'mediumblob', 'longblob'
1006
+ ].includes(base))
1007
+ return 'buffer';
1008
+ if ([
1009
+ 'json', 'geometry', 'point', 'polygon', 'multipoint', 'multilinestring', 'multipolygon', 'geometrycollection'
1010
+ ].includes(base))
1011
+ return 'object';
1012
+ if ([
1013
+ 'tinyint', 'smallint', 'mediumint', 'int', 'integer', 'bigint',
1014
+ 'decimal', 'dec', 'numeric', 'float', 'double', 'real'
1015
+ ].includes(base))
1016
+ return 'number';
1017
+ if ([
1018
+ 'boolean', 'bool'
1019
+ ].includes(base))
1020
+ return 'boolean';
1021
+ return 'string';
1022
+ }
1023
+ function getPrimaryKeyTypes(table) {
1024
+ var _a;
1025
+ var result = {};
1026
+ var _loop_1 = function (key) {
1027
+ var fullKey = (_a = Object.entries(table.COLUMNS).find(function (_a) {
1028
+ _a[0]; var short = _a[1];
1029
+ return short === key;
1030
+ })) === null || _a === void 0 ? void 0 : _a[0];
1031
+ if (typeof fullKey === 'string') {
1032
+ var validation = table.TYPE_VALIDATION[fullKey];
1033
+ if (!validation)
1034
+ return "continue";
1035
+ result[key] = determineRuntimeJsType(validation.MYSQL_TYPE);
1036
+ }
1037
+ };
1038
+ for (var _i = 0, _b = table.PRIMARY_SHORT; _i < _b.length; _i++) {
1039
+ var key = _b[_i];
1040
+ _loop_1(key);
1041
+ }
1042
+ return result;
1043
+ }
1044
+
1353
1045
  /**
1354
1046
  * Conditionally group a log if verbose.
1355
1047
  */
@@ -1405,5 +1097,5 @@ function onError(message) {
1405
1097
  toast.error(message, isDevelopment ? toastOptionsDevs : toastOptions);
1406
1098
  }
1407
1099
 
1408
- export { C6Constants, DELETE, Executor, GET, HttpExecutor, POST, PUT, SqlExecutor, TestRestfulResponse, apiRequestCache, axiosInstance, buildAggregateField, buildBooleanJoinedConditions, buildSelectQuery, checkAllRequestsComplete, checkCache, clearCache, convertForRequestBody, eFetchDependencies, error, extendedTypeHints, getEnvVar, group, info, isDevelopment as isLocal, isNode, isPromise, isTest, isVerbose, onError, onSuccess, removeInvalidKeys, removePrefixIfExists, restRequest, sortAndSerializeQueryObject, timeout, toastOptions, toastOptionsDevs, userCustomClearCache, warn };
1100
+ export { C6Constants, DELETE, Executor, GET, HttpExecutor, POST, PUT, SqlExecutor, TestRestfulResponse, apiRequestCache, axiosInstance, buildAggregateField, buildBooleanJoinedConditions, buildSelectQuery, checkAllRequestsComplete, checkCache, clearCache, convertForRequestBody, determineRuntimeJsType, eFetchDependencies, error, getEnvVar, getPrimaryKeyTypes, group, info, isDevelopment as isLocal, isNode, isPromise, isTest, isVerbose, onError, onSuccess, removeInvalidKeys, removePrefixIfExists, restOrm, restRequest, sortAndSerializeQueryObject, timeout, toastOptions, toastOptionsDevs, userCustomClearCache, warn };
1409
1101
  //# sourceMappingURL=index.esm.js.map