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