@carbonorm/carbonnode 3.0.2 → 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";
@@ -685,18 +738,71 @@ var HttpExecutor = /** @class */ (function (_super) {
685
738
  function HttpExecutor() {
686
739
  return _super !== null && _super.apply(this, arguments) || this;
687
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
+ };
688
789
  HttpExecutor.prototype.execute = function () {
689
790
  return __awaiter(this, void 0, void 0, function () {
690
- var _a, C6, axios, restURL, withCredentials, restModel, requestMethod, queryCallback, responseCallback, skipPrimaryCheck, clearCache, tableName, fullTableList, operatingTableFullName, operatingTable, tables, query, apiRequest;
691
- var _this = this;
791
+ var _a, C6, restModel, requestMethod, clearCache, tableName, fullTableList, operatingTableFullName, tables;
692
792
  return __generator(this, function (_b) {
693
793
  switch (_b.label) {
694
794
  case 0:
695
- _a = this.config, C6 = _a.C6, axios = _a.axios, restURL = _a.restURL, withCredentials = _a.withCredentials, restModel = _a.restModel, 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();
696
802
  tableName = restModel.TABLE_NAME;
697
803
  fullTableList = Array.isArray(tableName) ? tableName : [tableName];
698
804
  operatingTableFullName = fullTableList[0];
699
- operatingTable = removePrefixIfExists(operatingTableFullName, C6.PREFIX);
805
+ removePrefixIfExists(operatingTableFullName, C6.PREFIX);
700
806
  tables = fullTableList.join(',');
701
807
  switch (requestMethod) {
702
808
  case GET:
@@ -713,13 +819,7 @@ var HttpExecutor = /** @class */ (function (_super) {
713
819
  console.groupCollapsed('%c API: (' + requestMethod + ') Request for (' + tableName + ')', 'color: #0c0');
714
820
  console.log('request', this.request);
715
821
  console.groupEnd();
716
- if ('function' === typeof queryCallback) {
717
- query = queryCallback(this.request); // obj or obj[]
718
- }
719
- else {
720
- query = queryCallback;
721
- }
722
- if (undefined === query || null === query) {
822
+ {
723
823
  if (this.request.debug && isDevelopment) {
724
824
  toast.warning("DEV: queryCallback returned undefined, signaling in Custom Cache. (returning null)", toastOptionsDevs);
725
825
  }
@@ -729,456 +829,7 @@ var HttpExecutor = /** @class */ (function (_super) {
729
829
  console.groupEnd();
730
830
  return [2 /*return*/, null];
731
831
  }
732
- if (C6.GET === requestMethod) {
733
- if (undefined === query[C6.PAGINATION]) {
734
- query[C6.PAGINATION] = {};
735
- }
736
- query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
737
- query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
738
- }
739
- apiRequest = function () { return __awaiter(_this, void 0, void 0, function () {
740
- 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;
741
- var _e;
742
- var _this = this;
743
- var _f, _g, _h, _j, _k, _l;
744
- return __generator(this, function (_m) {
745
- _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;
746
- if (C6.GET === requestMethod
747
- && undefined !== ((_f = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _f === void 0 ? void 0 : _f[C6.PAGE])
748
- && 1 !== query[C6.PAGINATION][C6.PAGE]) {
749
- console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
750
- console.log('Request Data (note you may see the success and/or error prompt):', this.request);
751
- console.trace();
752
- console.groupEnd();
753
- }
754
- querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
755
- cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
756
- cachingConfirmed = false;
757
- // determine if we need to paginate.
758
- if (requestMethod === C6.GET) {
759
- if (undefined === (query === null || query === void 0 ? void 0 : query[C6.PAGINATION])) {
760
- if (undefined === query || null === query) {
761
- query = {};
762
- }
763
- query[C6.PAGINATION] = {};
764
- }
765
- query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
766
- query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
767
- // this will evaluate true most the time
768
- if (true === cacheResults) {
769
- // just find the next, non-fetched, page and return a function to request it
770
- if (undefined !== cacheResult) {
771
- do {
772
- cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
773
- if (false !== cacheCheck) {
774
- return [2 /*return*/, cacheCheck];
775
- }
776
- // this line incrementing page is why we return recursively
777
- ++query[C6.PAGINATION][C6.PAGE];
778
- // this json stringify is to capture the new page number
779
- querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
780
- cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
781
- } while (undefined !== cacheResult);
782
- if (debug && isDevelopment) {
783
- 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);
784
- }
785
- // @ts-ignore - this is an incorrect warning on TS, it's well typed
786
- return [2 /*return*/, apiRequest];
787
- }
788
- cachingConfirmed = true;
789
- }
790
- else {
791
- if (debug && isDevelopment) {
792
- toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
793
- }
794
- }
795
- if (debug && isDevelopment) {
796
- toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
797
- }
798
- }
799
- else if (cacheResults) { // if we are not getting, we are updating, deleting, or inserting
800
- if (cacheResult) {
801
- cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
802
- if (false !== cacheCheck) {
803
- return [2 /*return*/, cacheCheck];
804
- }
805
- }
806
- cachingConfirmed = true;
807
- // push to cache so we do not repeat the request
808
- }
809
- returnGetNextPageFunction = false;
810
- restRequestUri = restURL + operatingTable + '/';
811
- needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
812
- && false === skipPrimaryCheck;
813
- TABLES = C6.TABLES;
814
- 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();
815
- if (needsConditionOrPrimaryCheck) {
816
- if (undefined === primaryKey) {
817
- if (null === query
818
- || undefined === query
819
- || undefined === (query === null || query === void 0 ? void 0 : query[C6.WHERE])
820
- || (true === Array.isArray(query[C6.WHERE])
821
- || query[C6.WHERE].length === 0)
822
- || (Object.keys(query === null || query === void 0 ? void 0 : query[C6.WHERE]).length === 0)) {
823
- console.error(query);
824
- 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 + ').');
825
- }
826
- }
827
- else {
828
- if (undefined === query
829
- || null === query
830
- || false === primaryKey in query) {
831
- if (true === debug && isDevelopment) {
832
- toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
833
- }
834
- throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(this.request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
835
- }
836
- if (undefined === (query === null || query === void 0 ? void 0 : query[primaryKey])
837
- || null === (query === null || query === void 0 ? void 0 : query[primaryKey])) {
838
- toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!');
839
- throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
840
- }
841
- }
842
- }
843
- // A part of me exists that wants to remove this, but it's a good feature
844
- // this allows developers the ability to cache requests based on primary key
845
- // for tables like `photos` this can be a huge performance boost
846
- if (undefined !== query
847
- && null !== query
848
- && undefined !== primaryKey
849
- && primaryKey in query) {
850
- restRequestUri += query[primaryKey] + '/';
851
- removedPkValue_1 = query[primaryKey];
852
- addBackPK = function () {
853
- query !== null && query !== void 0 ? query : (query = {});
854
- query[primaryKey] = removedPkValue_1;
855
- };
856
- delete query[primaryKey];
857
- console.log('query', query, 'primaryKey', primaryKey, 'removedPkValue', removedPkValue_1);
858
- }
859
- else {
860
- console.log('query', query);
861
- }
862
- try {
863
- console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
864
- console.log(this.request);
865
- 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');
866
- 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');
867
- console.trace();
868
- console.groupEnd();
869
- axiosActiveRequest = (_e = axios)[requestMethod.toLowerCase()].apply(_e, __spreadArray([restRequestUri], ((function () {
870
- // @link - https://axios-http.com/docs/instance
871
- // How configuration vs data is passed is variable, use documentation above for reference
872
- if (requestMethod === GET) {
873
- return [{
874
- withCredentials: withCredentials,
875
- params: query
876
- }];
877
- }
878
- else if (requestMethod === POST) {
879
- if (undefined !== dataInsertMultipleRows) {
880
- return [
881
- dataInsertMultipleRows.map(function (data) {
882
- return convertForRequestBody(data, fullTableList, C6, function (message) { return toast.error(message, toastOptions); });
883
- }),
884
- {
885
- withCredentials: withCredentials,
886
- }
887
- ];
888
- }
889
- return [
890
- convertForRequestBody(query, fullTableList, C6, function (message) { return toast.error(message, toastOptions); }),
891
- {
892
- withCredentials: withCredentials,
893
- }
894
- ];
895
- }
896
- else if (requestMethod === PUT) {
897
- return [
898
- convertForRequestBody(query, fullTableList, C6, function (message) { return toast.error(message, toastOptions); }),
899
- {
900
- withCredentials: withCredentials,
901
- }
902
- ];
903
- }
904
- else if (requestMethod === DELETE) {
905
- return [{
906
- withCredentials: withCredentials,
907
- data: convertForRequestBody(query, fullTableList, C6, function (message) { return toast.error(message, toastOptions); })
908
- }];
909
- }
910
- else {
911
- throw new Error('The request method (' + requestMethod + ') was not recognized.');
912
- }
913
- })()), false));
914
- if (cachingConfirmed) {
915
- // push to cache so we do not repeat the request
916
- apiRequestCache.push({
917
- requestArgumentsSerialized: querySerialized,
918
- request: axiosActiveRequest
919
- });
920
- }
921
- // todo - wip verify this works
922
- // we had removed the value from the request to add to the URI.
923
- addBackPK === null || addBackPK === void 0 ? void 0 : addBackPK(); // adding back so post-processing methods work
924
- // returning the promise with this then is important for tests. todo - we could make that optional.
925
- // https://rapidapi.com/guides/axios-async-await
926
- return [2 /*return*/, axiosActiveRequest.then(function (response) { return __awaiter(_this, void 0, void 0, function () {
927
- var cacheIndex, responseData_1, dependencies_1, fetchReferences_1, apiRequestPromises, _loop_1, _a, _b, _c, _i, tableToFetch;
928
- var _this = this;
929
- var _d, _e, _f, _g, _h, _j, _k;
930
- return __generator(this, function (_l) {
931
- switch (_l.label) {
932
- case 0:
933
- if (typeof response.data === 'string') {
934
- if (isTest) {
935
- console.trace();
936
- 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 + ')');
937
- }
938
- return [2 /*return*/, Promise.reject(response)];
939
- }
940
- if (cachingConfirmed) {
941
- cacheIndex = apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
942
- apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction;
943
- // only cache get method requests
944
- apiRequestCache[cacheIndex].response = response;
945
- }
946
- apiResponse = TestRestfulResponse(response, success, error);
947
- if (false === apiResponse) {
948
- if (debug && isDevelopment) {
949
- toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
950
- }
951
- return [2 /*return*/, response];
952
- }
953
- // stateful operations are done in the response callback - its leverages rest generated functions
954
- if (responseCallback) {
955
- responseCallback(response, this.request, apiResponse);
956
- }
957
- if (!(C6.GET === requestMethod)) return [3 /*break*/, 6];
958
- responseData_1 = response.data;
959
- returnGetNextPageFunction = 1 !== ((_d = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _d === void 0 ? void 0 : _d[C6.LIMIT]) &&
960
- ((_e = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _e === void 0 ? void 0 : _e[C6.LIMIT]) === responseData_1.rest.length;
961
- if (false === isTest || true === isVerbose) {
962
- 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');
963
- console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
964
- console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', this.request);
965
- console.log('%c Response Data:', 'color: #0c0', responseData_1.rest);
966
- 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);
967
- console.trace();
968
- console.groupEnd();
969
- }
970
- if (false === returnGetNextPageFunction
971
- && true === debug
972
- && isDevelopment) {
973
- 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);
974
- }
975
- if (!(fetchDependencies
976
- && 'number' === typeof fetchDependencies
977
- && responseData_1.rest.length > 0)) return [3 /*break*/, 6];
978
- console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
979
- + (fetchDependencies & eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
980
- + (fetchDependencies & eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
981
- + (fetchDependencies & eFetchDependencies.C6ENTITY ? ' | (C6ENTITY)' : '')
982
- + (fetchDependencies & eFetchDependencies.RECURSIVE ? ' | (RECURSIVE)' : ''), 'color: #33ccff');
983
- console.groupCollapsed('Collapsed JS Trace');
984
- console.trace(); // hidden in collapsed group
985
- console.groupEnd();
986
- dependencies_1 = {};
987
- if (fetchDependencies & eFetchDependencies.C6ENTITY) {
988
- dependencies_1 = operatingTable.endsWith("carbon_carbons")
989
- ? __assign(__assign({}, fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
990
- ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
991
- : {}), fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
992
- ? C6.TABLES[operatingTable].TABLE_REFERENCES
993
- : {}) : __assign(__assign({}, fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
994
- ? __assign(__assign({}, Object.keys(C6.TABLES[operatingTable].TABLE_REFERENCES).reduce(function (accumulator, columnName) {
995
- if (!C6.TABLES[operatingTable].PRIMARY_SHORT.includes(columnName)) {
996
- accumulator[columnName] = C6.TABLES[operatingTable].TABLE_REFERENCES[columnName];
997
- }
998
- return accumulator;
999
- }, {})), C6.TABLES[operatingTable].TABLE_REFERENCED_BY // it is unlikely that a C6 table will have any TABLE_REFERENCED_BY
1000
- ) : {}), fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
1001
- ? C6.TABLES[operatingTable].PRIMARY_SHORT.reduce(function (accumulator, primaryKey) {
1002
- if (primaryKey in C6.TABLES[operatingTable].TABLE_REFERENCES) {
1003
- accumulator[primaryKey] = C6.TABLES[operatingTable].TABLE_REFERENCES[primaryKey];
1004
- }
1005
- return accumulator;
1006
- }, {})
1007
- : {});
1008
- }
1009
- else {
1010
- // this is the natural mysql context
1011
- dependencies_1 = __assign(__assign({}, fetchDependencies & eFetchDependencies.REFERENCED // REFERENCED === CHILDREN
1012
- ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1013
- : {}), fetchDependencies & eFetchDependencies.REFERENCES // REFERENCES === PARENTS
1014
- ? C6.TABLES[operatingTable].TABLE_REFERENCES
1015
- : {});
1016
- }
1017
- fetchReferences_1 = {};
1018
- apiRequestPromises = [];
1019
- console.log('%c Dependencies', 'color: #005555', dependencies_1);
1020
- Object.keys(dependencies_1)
1021
- .forEach(function (column) { return dependencies_1[column]
1022
- .forEach(function (constraint) {
1023
- var _a, _b, _c, _d;
1024
- var _e, _f, _g;
1025
- var columnValues = (_b = (_a = responseData_1.rest[column]) !== null && _a !== void 0 ? _a : responseData_1.rest.map(function (row) {
1026
- if (operatingTable.endsWith("carbons")
1027
- && 'entity_tag' in row
1028
- && !constraint.TABLE.endsWith(row['entity_tag'].split('\\').pop().toLowerCase())) {
1029
- return false; // map
1030
- }
1031
- if (!(column in row)) {
1032
- return false;
1033
- }
1034
- // todo - row[column] is a FK value, we should optionally remove values that are already in state
1035
- // this could be any column in the table constraint.TABLE, not just the primary key
1036
- return row[column];
1037
- }).filter(function (n) { return n; })) !== null && _b !== void 0 ? _b : [];
1038
- if (columnValues.length === 0) {
1039
- return; // forEach
1040
- }
1041
- (_c = fetchReferences_1[_e = constraint.TABLE]) !== null && _c !== void 0 ? _c : (fetchReferences_1[_e] = {});
1042
- (_d = (_f = fetchReferences_1[constraint.TABLE])[_g = constraint.COLUMN]) !== null && _d !== void 0 ? _d : (_f[_g] = []);
1043
- fetchReferences_1[constraint.TABLE][constraint.COLUMN].push(columnValues);
1044
- }); });
1045
- console.log('fetchReferences', fetchReferences_1);
1046
- _loop_1 = function (tableToFetch) {
1047
- var referencesTables, shouldContinue, fetchTable, RestApi, nextFetchDependencies;
1048
- var _m;
1049
- return __generator(this, function (_o) {
1050
- switch (_o.label) {
1051
- case 0:
1052
- if (fetchDependencies & eFetchDependencies.C6ENTITY
1053
- && 'string' === typeof tableName
1054
- && tableName.endsWith("carbon_carbons")) {
1055
- referencesTables = responseData_1.rest.reduce(function (accumulator, row) {
1056
- if ('entity_tag' in row && !accumulator.includes(row['entity_tag'])) {
1057
- accumulator.push(row['entity_tag']);
1058
- }
1059
- return accumulator;
1060
- }, []).map(function (entityTag) { return entityTag.split('\\').pop().toLowerCase(); });
1061
- shouldContinue = referencesTables.find(function (referencesTable) { return tableToFetch.endsWith(referencesTable); });
1062
- if (!shouldContinue) {
1063
- console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables);
1064
- return [2 /*return*/, "continue"];
1065
- }
1066
- console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') will be fetched.', 'color: #0c0');
1067
- }
1068
- return [4 /*yield*/, C6.IMPORT(tableToFetch)];
1069
- case 1:
1070
- fetchTable = _o.sent();
1071
- RestApi = fetchTable.default;
1072
- console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff');
1073
- nextFetchDependencies = eFetchDependencies.NONE;
1074
- if (fetchDependencies & eFetchDependencies.RECURSIVE) {
1075
- if (fetchDependencies & eFetchDependencies.ALL) {
1076
- 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.');
1077
- }
1078
- nextFetchDependencies = fetchDependencies;
1079
- }
1080
- else if (fetchDependencies & eFetchDependencies.C6ENTITY) {
1081
- if (tableToFetch === "carbon_carbons") {
1082
- nextFetchDependencies = fetchDependencies;
1083
- }
1084
- else {
1085
- nextFetchDependencies = fetchDependencies ^ eFetchDependencies.C6ENTITY;
1086
- }
1087
- }
1088
- console.log('fetchReferences', fetchReferences_1[tableToFetch], "Current fetchDependencies for (" + operatingTable + "):", fetchDependencies, "New fetchDependencies for (" + tableToFetch + "): ", nextFetchDependencies);
1089
- // 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
1090
- // it not certain that they are using carbons' entities either
1091
- // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
1092
- // todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
1093
- apiRequestPromises.push(RestApi.Get((_m = {},
1094
- _m[C6.WHERE] = {
1095
- 0: Object.keys(fetchReferences_1[tableToFetch]).reduce(function (sum, column) {
1096
- fetchReferences_1[tableToFetch][column] = fetchReferences_1[tableToFetch][column].flat(Infinity);
1097
- if (0 === fetchReferences_1[tableToFetch][column].length) {
1098
- console.warn('The column (' + column + ') was not found in the response data. We will not fetch.', responseData_1);
1099
- return false;
1100
- }
1101
- sum[column] = fetchReferences_1[tableToFetch][column].length === 1
1102
- ? fetchReferences_1[tableToFetch][column][0]
1103
- : [
1104
- C6.IN, fetchReferences_1[tableToFetch][column]
1105
- ];
1106
- return sum;
1107
- }, {})
1108
- },
1109
- _m.fetchDependencies = nextFetchDependencies,
1110
- _m)));
1111
- return [2 /*return*/];
1112
- }
1113
- });
1114
- };
1115
- _a = fetchReferences_1;
1116
- _b = [];
1117
- for (_c in _a)
1118
- _b.push(_c);
1119
- _i = 0;
1120
- _l.label = 1;
1121
- case 1:
1122
- if (!(_i < _b.length)) return [3 /*break*/, 4];
1123
- _c = _b[_i];
1124
- if (!(_c in _a)) return [3 /*break*/, 3];
1125
- tableToFetch = _c;
1126
- return [5 /*yield**/, _loop_1(tableToFetch)];
1127
- case 2:
1128
- _l.sent();
1129
- _l.label = 3;
1130
- case 3:
1131
- _i++;
1132
- return [3 /*break*/, 1];
1133
- case 4:
1134
- console.groupEnd();
1135
- return [4 /*yield*/, Promise.all(apiRequestPromises)];
1136
- case 5:
1137
- _l.sent();
1138
- apiRequestPromises.map(function (promise) { return __awaiter(_this, void 0, void 0, function () {
1139
- var _a, _b;
1140
- return __generator(this, function (_c) {
1141
- switch (_c.label) {
1142
- case 0:
1143
- if (!Array.isArray(this.request.fetchDependencies)) {
1144
- // to reassign value we must ref the root
1145
- this.request.fetchDependencies = [];
1146
- }
1147
- _b = (_a = this.request.fetchDependencies).push;
1148
- return [4 /*yield*/, promise];
1149
- case 1:
1150
- _b.apply(_a, [_c.sent()]);
1151
- return [2 /*return*/];
1152
- }
1153
- });
1154
- }); });
1155
- _l.label = 6;
1156
- case 6:
1157
- if (debug && isDevelopment) {
1158
- toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1159
- }
1160
- return [2 /*return*/, response];
1161
- }
1162
- });
1163
- }); })];
1164
- }
1165
- catch (throwableError) {
1166
- if (isTest) {
1167
- throw new Error(JSON.stringify(throwableError));
1168
- }
1169
- console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
1170
- console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
1171
- console.warn(throwableError);
1172
- console.trace();
1173
- console.groupEnd();
1174
- TestRestfulResponse(throwableError, success, error);
1175
- return [2 /*return*/, null];
1176
- }
1177
- return [2 /*return*/];
1178
- });
1179
- }); };
1180
- return [4 /*yield*/, apiRequest()];
1181
- case 1: return [2 /*return*/, _b.sent()];
832
+ case 2: return [2 /*return*/, _b.sent()];
1182
833
  }
1183
834
  });
1184
835
  });
@@ -1446,5 +1097,5 @@ function onError(message) {
1446
1097
  toast.error(message, isDevelopment ? toastOptionsDevs : toastOptions);
1447
1098
  }
1448
1099
 
1449
- 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, 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 };
1450
1101
  //# sourceMappingURL=index.esm.js.map