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