@carbonorm/carbonnode 3.0.9 → 3.0.11

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
@@ -308,8 +308,7 @@ function convertForRequestBody (restfulObject, tableName, C6, regexErrorHandler)
308
308
  }, {});
309
309
  }
310
310
 
311
- var _a;
312
- var isNode = typeof process !== 'undefined' && !!((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node);
311
+ var isNode = function () { var _a; return typeof process !== 'undefined' && !!((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node); };
313
312
 
314
313
  /**
315
314
  * Facade: routes API calls to SQL or HTTP executors based on runtime context.
@@ -322,7 +321,7 @@ function restRequest(configX) {
322
321
  switch (_a.label) {
323
322
  case 0:
324
323
  config = typeof configX === "function" ? configX() : configX;
325
- if (!(isNode && config.mysqlPool)) return [3 /*break*/, 2];
324
+ if (!(isNode() && config.mysqlPool)) return [3 /*break*/, 2];
326
325
  return [4 /*yield*/, Promise.resolve().then(function () { return SqlExecutor$1; })];
327
326
  case 1:
328
327
  SqlExecutor = (_a.sent()).SqlExecutor;
@@ -339,12 +338,11 @@ function restRequest(configX) {
339
338
  }
340
339
 
341
340
  function restOrm(config) {
342
- return {
343
- Get: restRequest(function () { return (__assign(__assign({}, config()), { requestMethod: "GET" })); }),
344
- Put: restRequest(function () { return (__assign(__assign({}, config()), { requestMethod: "PUT" })); }),
345
- Post: restRequest(function () { return (__assign(__assign({}, config()), { requestMethod: "POST" })); }),
346
- Delete: restRequest(function () { return (__assign(__assign({}, config()), { requestMethod: "DELETE" })); }),
347
- };
341
+ var methods = ["GET", "PUT", "POST", "DELETE"];
342
+ return Object.fromEntries(methods.map(function (method) { return [
343
+ method[0] + method.slice(1).toLowerCase(), // Capitalize e.g. "Get"
344
+ restRequest(function () { return (__assign(__assign({}, config()), { requestMethod: method })); })
345
+ ]; }));
348
346
  }
349
347
 
350
348
  function timeout(shouldContinueAfterTimeout, cb, timeoutMs) {
@@ -828,458 +826,466 @@ var HttpExecutor = /** @class */ (function (_super) {
828
826
  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;
829
827
  var _e;
830
828
  var _this = this;
831
- var _f, _g, _h, _j, _k, _l;
832
- return __generator(this, function (_m) {
833
- _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;
834
- if (C6.GET === requestMethod
835
- && undefined !== ((_f = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _f === void 0 ? void 0 : _f[C6.PAGE])
836
- && 1 !== query[C6.PAGINATION][C6.PAGE]) {
837
- console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
838
- console.log('Request Data (note you may see the success and/or error prompt):', this.request);
839
- console.trace();
840
- console.groupEnd();
841
- }
842
- querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
843
- cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
844
- cachingConfirmed = false;
845
- // determine if we need to paginate.
846
- if (requestMethod === C6.GET) {
847
- if (undefined === (query === null || query === void 0 ? void 0 : query[C6.PAGINATION])) {
848
- if (undefined === query || null === query) {
849
- query = {};
829
+ var _f, _g, _h, _j, _k, _l, _m, _o;
830
+ return __generator(this, function (_p) {
831
+ switch (_p.label) {
832
+ case 0:
833
+ _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;
834
+ if (C6.GET === requestMethod
835
+ && undefined !== ((_f = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _f === void 0 ? void 0 : _f[C6.PAGE])
836
+ && 1 !== query[C6.PAGINATION][C6.PAGE]) {
837
+ console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
838
+ console.log('Request Data (note you may see the success and/or error prompt):', this.request);
839
+ console.trace();
840
+ console.groupEnd();
850
841
  }
851
- query[C6.PAGINATION] = {};
852
- }
853
- query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
854
- query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
855
- // this will evaluate true most the time
856
- if (true === cacheResults) {
857
- // just find the next, non-fetched, page and return a function to request it
858
- if (undefined !== cacheResult) {
859
- do {
860
- cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
861
- if (false !== cacheCheck) {
862
- return [2 /*return*/, cacheCheck];
863
- }
864
- // this line incrementing page is why we return recursively
865
- ++query[C6.PAGINATION][C6.PAGE];
866
- // this json stringify is to capture the new page number
867
- querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
868
- cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
869
- } while (undefined !== cacheResult);
870
- if (debug && isDevelopment) {
871
- 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);
842
+ querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
843
+ cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
844
+ cachingConfirmed = false;
845
+ if (!(requestMethod === C6.GET)) return [3 /*break*/, 9];
846
+ if (undefined === (query === null || query === void 0 ? void 0 : query[C6.PAGINATION])) {
847
+ if (undefined === query || null === query) {
848
+ query = {};
872
849
  }
873
- // @ts-ignore - this is an incorrect warning on TS, it's well typed
874
- return [2 /*return*/, apiRequest];
850
+ query[C6.PAGINATION] = {};
875
851
  }
852
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
853
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
854
+ if (!(true === cacheResults)) return [3 /*break*/, 7];
855
+ if (!(undefined !== cacheResult)) return [3 /*break*/, 6];
856
+ _p.label = 1;
857
+ case 1:
858
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
859
+ if (!(false !== cacheCheck)) return [3 /*break*/, 3];
860
+ return [4 /*yield*/, cacheCheck];
861
+ case 2: return [2 /*return*/, (_g = (_p.sent())) === null || _g === void 0 ? void 0 : _g.data];
862
+ case 3:
863
+ // this line incrementing page is why we return recursively
864
+ ++query[C6.PAGINATION][C6.PAGE];
865
+ // this json stringify is to capture the new page number
866
+ querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
867
+ cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
868
+ _p.label = 4;
869
+ case 4:
870
+ if (undefined !== cacheResult) return [3 /*break*/, 1];
871
+ _p.label = 5;
872
+ case 5:
873
+ if (debug && isDevelopment) {
874
+ 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);
875
+ }
876
+ // @ts-ignore - this is an incorrect warning on TS, it's well typed
877
+ return [2 /*return*/, apiRequest];
878
+ case 6:
876
879
  cachingConfirmed = true;
877
- }
878
- else {
880
+ return [3 /*break*/, 8];
881
+ case 7:
879
882
  if (debug && isDevelopment) {
880
883
  toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
881
884
  }
882
- }
883
- if (debug && isDevelopment) {
884
- toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
885
- }
886
- }
887
- else if (cacheResults) { // if we are not getting, we are updating, deleting, or inserting
888
- if (cacheResult) {
889
- cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
890
- if (false !== cacheCheck) {
891
- return [2 /*return*/, cacheCheck];
892
- }
893
- }
894
- cachingConfirmed = true;
895
- // push to cache so we do not repeat the request
896
- }
897
- returnGetNextPageFunction = false;
898
- restRequestUri = restURL + operatingTable + '/';
899
- needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
900
- && false === skipPrimaryCheck;
901
- TABLES = C6.TABLES;
902
- 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();
903
- if (needsConditionOrPrimaryCheck) {
904
- if (undefined === primaryKey) {
905
- if (null === query
906
- || undefined === query
907
- || undefined === (query === null || query === void 0 ? void 0 : query[C6.WHERE])
908
- || (true === Array.isArray(query[C6.WHERE])
909
- || query[C6.WHERE].length === 0)
910
- || (Object.keys(query === null || query === void 0 ? void 0 : query[C6.WHERE]).length === 0)) {
911
- console.error(query);
912
- 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 + ').');
885
+ _p.label = 8;
886
+ case 8:
887
+ if (debug && isDevelopment) {
888
+ toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
913
889
  }
914
- }
915
- else {
916
- if (undefined === query
917
- || null === query
918
- || false === primaryKey in query) {
919
- if (true === debug && isDevelopment) {
920
- toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
890
+ return [3 /*break*/, 12];
891
+ case 9:
892
+ if (!cacheResults) return [3 /*break*/, 12];
893
+ if (!cacheResult) return [3 /*break*/, 11];
894
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
895
+ if (!(false !== cacheCheck)) return [3 /*break*/, 11];
896
+ return [4 /*yield*/, cacheCheck];
897
+ case 10: return [2 /*return*/, (_h = (_p.sent())) === null || _h === void 0 ? void 0 : _h.data];
898
+ case 11:
899
+ cachingConfirmed = true;
900
+ _p.label = 12;
901
+ case 12:
902
+ returnGetNextPageFunction = false;
903
+ restRequestUri = restURL + operatingTable + '/';
904
+ needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
905
+ && false === skipPrimaryCheck;
906
+ TABLES = C6.TABLES;
907
+ primaryKey = (_m = (_l = (_k = structuredClone((_j = TABLES[operatingTable]) === null || _j === void 0 ? void 0 : _j.PRIMARY)) === null || _k === void 0 ? void 0 : _k.pop()) === null || _l === void 0 ? void 0 : _l.split('.')) === null || _m === void 0 ? void 0 : _m.pop();
908
+ if (needsConditionOrPrimaryCheck) {
909
+ if (undefined === primaryKey) {
910
+ if (null === query
911
+ || undefined === query
912
+ || undefined === (query === null || query === void 0 ? void 0 : query[C6.WHERE])
913
+ || (true === Array.isArray(query[C6.WHERE])
914
+ || query[C6.WHERE].length === 0)
915
+ || (Object.keys(query === null || query === void 0 ? void 0 : query[C6.WHERE]).length === 0)) {
916
+ console.error(query);
917
+ throw Error('Failed to parse primary key information. Query: (' + JSON.stringify(query) + ') Primary Key: (' + JSON.stringify(primaryKey) + ') TABLES[operatingTable]?.PRIMARY: (' + JSON.stringify((_o = TABLES[operatingTable]) === null || _o === void 0 ? void 0 : _o.PRIMARY) + ') for operatingTable (' + operatingTable + ').');
918
+ }
919
+ }
920
+ else {
921
+ if (undefined === query
922
+ || null === query
923
+ || false === primaryKey in query) {
924
+ if (true === debug && isDevelopment) {
925
+ toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
926
+ }
927
+ throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(this.request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
928
+ }
929
+ if (undefined === (query === null || query === void 0 ? void 0 : query[primaryKey])
930
+ || null === (query === null || query === void 0 ? void 0 : query[primaryKey])) {
931
+ toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!');
932
+ throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
933
+ }
921
934
  }
922
- throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(this.request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
923
935
  }
924
- if (undefined === (query === null || query === void 0 ? void 0 : query[primaryKey])
925
- || null === (query === null || query === void 0 ? void 0 : query[primaryKey])) {
926
- toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!');
927
- throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
936
+ // A part of me exists that wants to remove this, but it's a good feature
937
+ // this allows developers the ability to cache requests based on primary key
938
+ // for tables like `photos` this can be a huge performance boost
939
+ if (undefined !== query
940
+ && null !== query
941
+ && undefined !== primaryKey
942
+ && primaryKey in query) {
943
+ restRequestUri += query[primaryKey] + '/';
944
+ removedPkValue_1 = query[primaryKey];
945
+ addBackPK = function () {
946
+ query !== null && query !== void 0 ? query : (query = {});
947
+ query[primaryKey] = removedPkValue_1;
948
+ };
949
+ delete query[primaryKey];
950
+ console.log('query', query, 'primaryKey', primaryKey, 'removedPkValue', removedPkValue_1);
928
951
  }
929
- }
930
- }
931
- // A part of me exists that wants to remove this, but it's a good feature
932
- // this allows developers the ability to cache requests based on primary key
933
- // for tables like `photos` this can be a huge performance boost
934
- if (undefined !== query
935
- && null !== query
936
- && undefined !== primaryKey
937
- && primaryKey in query) {
938
- restRequestUri += query[primaryKey] + '/';
939
- removedPkValue_1 = query[primaryKey];
940
- addBackPK = function () {
941
- query !== null && query !== void 0 ? query : (query = {});
942
- query[primaryKey] = removedPkValue_1;
943
- };
944
- delete query[primaryKey];
945
- console.log('query', query, 'primaryKey', primaryKey, 'removedPkValue', removedPkValue_1);
946
- }
947
- else {
948
- console.log('query', query);
949
- }
950
- try {
951
- console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
952
- console.log(this.request);
953
- 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');
954
- 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');
955
- console.trace();
956
- console.groupEnd();
957
- this.runLifecycleHooks("beforeExecution", {
958
- config: this.config,
959
- request: this.request
960
- });
961
- axiosActiveRequest = (_e = axios)[requestMethod.toLowerCase()].apply(_e, __spreadArray([restRequestUri], (function () {
962
- var convert = function (data) {
963
- return convertForRequestBody(data, fullTableList, C6, function (message) { return toast.error(message, toastOptions); });
964
- };
965
- var baseConfig = {
966
- withCredentials: withCredentials,
967
- };
968
- switch (requestMethod) {
969
- case GET:
970
- return [__assign(__assign({}, baseConfig), { params: query })];
971
- case POST:
972
- if (dataInsertMultipleRows !== undefined) {
973
- return [
974
- dataInsertMultipleRows.map(convert),
975
- baseConfig
976
- ];
977
- }
978
- return [convert(query), baseConfig];
979
- case PUT:
980
- return [convert(query), baseConfig];
981
- case DELETE:
982
- return [__assign(__assign({}, baseConfig), { data: convert(query) })];
983
- default:
984
- throw new Error("The request method (".concat(requestMethod, ") was not recognized."));
952
+ else {
953
+ console.log('query', query);
985
954
  }
986
- })(), false));
987
- if (cachingConfirmed) {
988
- // push to cache so we do not repeat the request
989
- apiRequestCache.push({
990
- requestArgumentsSerialized: querySerialized,
991
- request: axiosActiveRequest
992
- });
993
- }
994
- // todo - wip verify this works
995
- // we had removed the value from the request to add to the URI.
996
- addBackPK === null || addBackPK === void 0 ? void 0 : addBackPK(); // adding back so post-processing methods work
997
- // returning the promise with this then is important for tests. todo - we could make that optional.
998
- // https://rapidapi.com/guides/axios-async-await
999
- return [2 /*return*/, axiosActiveRequest.then(function (response) { return __awaiter(_this, void 0, void 0, function () {
1000
- var cacheIndex, callback, responseData_1, dependencies_1, fetchReferences_1, apiRequestPromises, _loop_1, _a, _b, _c, _i, tableToFetch;
1001
- var _this = this;
1002
- var _d, _e, _f, _g, _h, _j, _k;
1003
- return __generator(this, function (_l) {
1004
- switch (_l.label) {
1005
- case 0:
1006
- // noinspection SuspiciousTypeOfGuard
1007
- if (typeof response.data === 'string') {
1008
- if (isTest) {
1009
- console.trace();
1010
- 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 + ')');
1011
- }
1012
- return [2 /*return*/, Promise.reject(response)];
1013
- }
1014
- if (cachingConfirmed) {
1015
- cacheIndex = apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
1016
- apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction;
1017
- // only cache get method requests
1018
- apiRequestCache[cacheIndex].response = response;
1019
- }
1020
- this.runLifecycleHooks("afterExecution", {
1021
- config: this.config,
1022
- request: this.request,
1023
- response: response
1024
- });
1025
- // todo - this feels dumb now, but i digress
1026
- apiResponse = TestRestfulResponse(response, success, error);
1027
- if (false === apiResponse) {
1028
- if (debug && isDevelopment) {
1029
- toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
1030
- }
1031
- return [2 /*return*/, response];
1032
- }
1033
- callback = function () { return _this.runLifecycleHooks("afterCommit", {
1034
- config: _this.config,
1035
- request: _this.request,
1036
- response: response
1037
- }); };
1038
- if (undefined !== reactBootstrap && response) {
1039
- switch (requestMethod) {
1040
- case GET:
1041
- reactBootstrap.updateRestfulObjectArrays({
1042
- dataOrCallback: Array.isArray(response.data.rest) ? response.data.rest : [response.data.rest],
1043
- stateKey: this.config.restModel.TABLE_NAME,
1044
- uniqueObjectId: this.config.restModel.PRIMARY_SHORT,
1045
- callback: callback
1046
- });
1047
- break;
1048
- case POST:
1049
- this.postState(response, this.request, callback);
1050
- break;
1051
- case PUT:
1052
- this.putState(response, this.request, callback);
1053
- break;
1054
- case DELETE:
1055
- this.deleteState(response, this.request, callback);
1056
- break;
1057
- }
1058
- }
1059
- else {
1060
- callback();
1061
- }
1062
- if (!(C6.GET === requestMethod)) return [3 /*break*/, 6];
1063
- responseData_1 = response.data;
1064
- returnGetNextPageFunction = 1 !== ((_d = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _d === void 0 ? void 0 : _d[C6.LIMIT]) &&
1065
- ((_e = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _e === void 0 ? void 0 : _e[C6.LIMIT]) === responseData_1.rest.length;
1066
- if (false === isTest || true === isVerbose) {
1067
- 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');
1068
- console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
1069
- console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', this.request);
1070
- console.log('%c Response Data:', 'color: #0c0', responseData_1.rest);
1071
- 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);
1072
- console.trace();
1073
- console.groupEnd();
1074
- }
1075
- if (false === returnGetNextPageFunction
1076
- && true === debug
1077
- && isDevelopment) {
1078
- 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);
955
+ try {
956
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
957
+ console.log(this.request);
958
+ 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');
959
+ 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');
960
+ console.trace();
961
+ console.groupEnd();
962
+ this.runLifecycleHooks("beforeExecution", {
963
+ config: this.config,
964
+ request: this.request
965
+ });
966
+ axiosActiveRequest = (_e = axios)[requestMethod.toLowerCase()].apply(_e, __spreadArray([restRequestUri], (function () {
967
+ var convert = function (data) {
968
+ return convertForRequestBody(data, fullTableList, C6, function (message) { return toast.error(message, toastOptions); });
969
+ };
970
+ var baseConfig = {
971
+ withCredentials: withCredentials,
972
+ };
973
+ switch (requestMethod) {
974
+ case GET:
975
+ return [__assign(__assign({}, baseConfig), { params: query })];
976
+ case POST:
977
+ if (dataInsertMultipleRows !== undefined) {
978
+ return [
979
+ dataInsertMultipleRows.map(convert),
980
+ baseConfig
981
+ ];
1079
982
  }
1080
- if (!(fetchDependencies
1081
- && 'number' === typeof fetchDependencies
1082
- && responseData_1.rest.length > 0)) return [3 /*break*/, 6];
1083
- console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
1084
- + (fetchDependencies & eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
1085
- + (fetchDependencies & eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
1086
- + (fetchDependencies & eFetchDependencies.C6ENTITY ? ' | (C6ENTITY)' : '')
1087
- + (fetchDependencies & eFetchDependencies.RECURSIVE ? ' | (RECURSIVE)' : ''), 'color: #33ccff');
1088
- console.groupCollapsed('Collapsed JS Trace');
1089
- console.trace(); // hidden in collapsed group
1090
- console.groupEnd();
1091
- dependencies_1 = {};
1092
- if (fetchDependencies & eFetchDependencies.C6ENTITY) {
1093
- dependencies_1 = operatingTable.endsWith("carbon_carbons")
1094
- ? __assign(__assign({}, fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
1095
- ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1096
- : {}), fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
1097
- ? C6.TABLES[operatingTable].TABLE_REFERENCES
1098
- : {}) : __assign(__assign({}, fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
1099
- ? __assign(__assign({}, Object.keys(C6.TABLES[operatingTable].TABLE_REFERENCES).reduce(function (accumulator, columnName) {
1100
- if (!C6.TABLES[operatingTable].PRIMARY_SHORT.includes(columnName)) {
1101
- accumulator[columnName] = C6.TABLES[operatingTable].TABLE_REFERENCES[columnName];
983
+ return [convert(query), baseConfig];
984
+ case PUT:
985
+ return [convert(query), baseConfig];
986
+ case DELETE:
987
+ return [__assign(__assign({}, baseConfig), { data: convert(query) })];
988
+ default:
989
+ throw new Error("The request method (".concat(requestMethod, ") was not recognized."));
990
+ }
991
+ })(), false));
992
+ if (cachingConfirmed) {
993
+ // push to cache so we do not repeat the request
994
+ apiRequestCache.push({
995
+ requestArgumentsSerialized: querySerialized,
996
+ request: axiosActiveRequest
997
+ });
998
+ }
999
+ // todo - wip verify this works
1000
+ // we had removed the value from the request to add to the URI.
1001
+ addBackPK === null || addBackPK === void 0 ? void 0 : addBackPK(); // adding back so post-processing methods work
1002
+ // returning the promise with this then is important for tests. todo - we could make that optional.
1003
+ // https://rapidapi.com/guides/axios-async-await
1004
+ return [2 /*return*/, axiosActiveRequest.then(function (response) { return __awaiter(_this, void 0, void 0, function () {
1005
+ var cacheIndex, callback, responseData_1, dependencies_1, fetchReferences_1, apiRequestPromises, _loop_1, _a, _b, _c, _i, tableToFetch;
1006
+ var _this = this;
1007
+ var _d, _e, _f, _g, _h, _j, _k;
1008
+ return __generator(this, function (_l) {
1009
+ switch (_l.label) {
1010
+ case 0:
1011
+ // noinspection SuspiciousTypeOfGuard
1012
+ if (typeof response.data === 'string') {
1013
+ if (isTest) {
1014
+ console.trace();
1015
+ 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 + ')');
1102
1016
  }
1103
- return accumulator;
1104
- }, {})), C6.TABLES[operatingTable].TABLE_REFERENCED_BY // it is unlikely that a C6 table will have any TABLE_REFERENCED_BY
1105
- ) : {}), fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
1106
- ? C6.TABLES[operatingTable].PRIMARY_SHORT.reduce(function (accumulator, primaryKey) {
1107
- if (primaryKey in C6.TABLES[operatingTable].TABLE_REFERENCES) {
1108
- accumulator[primaryKey] = C6.TABLES[operatingTable].TABLE_REFERENCES[primaryKey];
1017
+ return [2 /*return*/, Promise.reject(response)];
1018
+ }
1019
+ if (cachingConfirmed) {
1020
+ cacheIndex = apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
1021
+ apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction;
1022
+ // only cache get method requests
1023
+ apiRequestCache[cacheIndex].response = response;
1024
+ }
1025
+ this.runLifecycleHooks("afterExecution", {
1026
+ config: this.config,
1027
+ request: this.request,
1028
+ response: response
1029
+ });
1030
+ // todo - this feels dumb now, but i digress
1031
+ apiResponse = TestRestfulResponse(response, success, error);
1032
+ if (false === apiResponse) {
1033
+ if (debug && isDevelopment) {
1034
+ toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
1109
1035
  }
1110
- return accumulator;
1111
- }, {})
1112
- : {});
1113
- }
1114
- else {
1115
- // this is the natural mysql context
1116
- dependencies_1 = __assign(__assign({}, fetchDependencies & eFetchDependencies.REFERENCED // REFERENCED === CHILDREN
1117
- ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1118
- : {}), fetchDependencies & eFetchDependencies.REFERENCES // REFERENCES === PARENTS
1119
- ? C6.TABLES[operatingTable].TABLE_REFERENCES
1120
- : {});
1121
- }
1122
- fetchReferences_1 = {};
1123
- apiRequestPromises = [];
1124
- console.log('%c Dependencies', 'color: #005555', dependencies_1);
1125
- Object.keys(dependencies_1)
1126
- .forEach(function (column) { return dependencies_1[column]
1127
- .forEach(function (constraint) {
1128
- var _a, _b, _c, _d;
1129
- var _e, _f, _g;
1130
- var columnValues = (_b = (_a = responseData_1.rest[column]) !== null && _a !== void 0 ? _a : responseData_1.rest.map(function (row) {
1131
- if (operatingTable.endsWith("carbons")
1132
- && 'entity_tag' in row
1133
- && !constraint.TABLE.endsWith(row['entity_tag'].split('\\').pop().toLowerCase())) {
1134
- return false; // map
1036
+ return [2 /*return*/, response];
1135
1037
  }
1136
- if (!(column in row)) {
1137
- return false;
1038
+ callback = function () { return _this.runLifecycleHooks("afterCommit", {
1039
+ config: _this.config,
1040
+ request: _this.request,
1041
+ response: response
1042
+ }); };
1043
+ if (undefined !== reactBootstrap && response) {
1044
+ switch (requestMethod) {
1045
+ case GET:
1046
+ reactBootstrap.updateRestfulObjectArrays({
1047
+ dataOrCallback: Array.isArray(response.data.rest) ? response.data.rest : [response.data.rest],
1048
+ stateKey: this.config.restModel.TABLE_NAME,
1049
+ uniqueObjectId: this.config.restModel.PRIMARY_SHORT,
1050
+ callback: callback
1051
+ });
1052
+ break;
1053
+ case POST:
1054
+ this.postState(response, this.request, callback);
1055
+ break;
1056
+ case PUT:
1057
+ this.putState(response, this.request, callback);
1058
+ break;
1059
+ case DELETE:
1060
+ this.deleteState(response, this.request, callback);
1061
+ break;
1062
+ }
1138
1063
  }
1139
- // todo - row[column] is a FK value, we should optionally remove values that are already in state
1140
- // this could be any column in the table constraint.TABLE, not just the primary key
1141
- return row[column];
1142
- }).filter(function (n) { return n; })) !== null && _b !== void 0 ? _b : [];
1143
- if (columnValues.length === 0) {
1144
- return; // forEach
1145
- }
1146
- (_c = fetchReferences_1[_e = constraint.TABLE]) !== null && _c !== void 0 ? _c : (fetchReferences_1[_e] = {});
1147
- (_d = (_f = fetchReferences_1[constraint.TABLE])[_g = constraint.COLUMN]) !== null && _d !== void 0 ? _d : (_f[_g] = []);
1148
- fetchReferences_1[constraint.TABLE][constraint.COLUMN].push(columnValues);
1149
- }); });
1150
- console.log('fetchReferences', fetchReferences_1);
1151
- _loop_1 = function (tableToFetch) {
1152
- var referencesTables, shouldContinue, fetchTable, RestApi, nextFetchDependencies;
1153
- var _m;
1154
- return __generator(this, function (_o) {
1155
- switch (_o.label) {
1156
- case 0:
1157
- if (fetchDependencies & eFetchDependencies.C6ENTITY
1158
- && 'string' === typeof tableName
1159
- && tableName.endsWith("carbon_carbons")) {
1160
- referencesTables = responseData_1.rest.reduce(function (accumulator, row) {
1161
- if ('entity_tag' in row && !accumulator.includes(row['entity_tag'])) {
1162
- accumulator.push(row['entity_tag']);
1163
- }
1164
- return accumulator;
1165
- }, []).map(function (entityTag) { return entityTag.split('\\').pop().toLowerCase(); });
1166
- shouldContinue = referencesTables.find(function (referencesTable) { return tableToFetch.endsWith(referencesTable); });
1167
- if (!shouldContinue) {
1168
- console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables);
1169
- return [2 /*return*/, "continue"];
1064
+ else {
1065
+ callback();
1066
+ }
1067
+ if (!(C6.GET === requestMethod)) return [3 /*break*/, 6];
1068
+ responseData_1 = response.data;
1069
+ returnGetNextPageFunction = 1 !== ((_d = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _d === void 0 ? void 0 : _d[C6.LIMIT]) &&
1070
+ ((_e = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _e === void 0 ? void 0 : _e[C6.LIMIT]) === responseData_1.rest.length;
1071
+ if (false === isTest || true === isVerbose) {
1072
+ 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');
1073
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
1074
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', this.request);
1075
+ console.log('%c Response Data:', 'color: #0c0', responseData_1.rest);
1076
+ 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);
1077
+ console.trace();
1078
+ console.groupEnd();
1079
+ }
1080
+ if (false === returnGetNextPageFunction
1081
+ && true === debug
1082
+ && isDevelopment) {
1083
+ 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);
1084
+ }
1085
+ if (!(fetchDependencies
1086
+ && 'number' === typeof fetchDependencies
1087
+ && responseData_1.rest.length > 0)) return [3 /*break*/, 6];
1088
+ console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
1089
+ + (fetchDependencies & eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
1090
+ + (fetchDependencies & eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
1091
+ + (fetchDependencies & eFetchDependencies.C6ENTITY ? ' | (C6ENTITY)' : '')
1092
+ + (fetchDependencies & eFetchDependencies.RECURSIVE ? ' | (RECURSIVE)' : ''), 'color: #33ccff');
1093
+ console.groupCollapsed('Collapsed JS Trace');
1094
+ console.trace(); // hidden in collapsed group
1095
+ console.groupEnd();
1096
+ dependencies_1 = {};
1097
+ if (fetchDependencies & eFetchDependencies.C6ENTITY) {
1098
+ dependencies_1 = operatingTable.endsWith("carbon_carbons")
1099
+ ? __assign(__assign({}, fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
1100
+ ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1101
+ : {}), fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
1102
+ ? C6.TABLES[operatingTable].TABLE_REFERENCES
1103
+ : {}) : __assign(__assign({}, fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
1104
+ ? __assign(__assign({}, Object.keys(C6.TABLES[operatingTable].TABLE_REFERENCES).reduce(function (accumulator, columnName) {
1105
+ if (!C6.TABLES[operatingTable].PRIMARY_SHORT.includes(columnName)) {
1106
+ accumulator[columnName] = C6.TABLES[operatingTable].TABLE_REFERENCES[columnName];
1170
1107
  }
1171
- console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') will be fetched.', 'color: #0c0');
1172
- }
1173
- return [4 /*yield*/, C6.IMPORT(tableToFetch)];
1174
- case 1:
1175
- fetchTable = _o.sent();
1176
- RestApi = fetchTable.default;
1177
- console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff');
1178
- nextFetchDependencies = eFetchDependencies.NONE;
1179
- if (fetchDependencies & eFetchDependencies.RECURSIVE) {
1180
- if (fetchDependencies & eFetchDependencies.ALL) {
1181
- 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.');
1108
+ return accumulator;
1109
+ }, {})), C6.TABLES[operatingTable].TABLE_REFERENCED_BY // it is unlikely that a C6 table will have any TABLE_REFERENCED_BY
1110
+ ) : {}), fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
1111
+ ? C6.TABLES[operatingTable].PRIMARY_SHORT.reduce(function (accumulator, primaryKey) {
1112
+ if (primaryKey in C6.TABLES[operatingTable].TABLE_REFERENCES) {
1113
+ accumulator[primaryKey] = C6.TABLES[operatingTable].TABLE_REFERENCES[primaryKey];
1182
1114
  }
1183
- nextFetchDependencies = fetchDependencies;
1115
+ return accumulator;
1116
+ }, {})
1117
+ : {});
1118
+ }
1119
+ else {
1120
+ // this is the natural mysql context
1121
+ dependencies_1 = __assign(__assign({}, fetchDependencies & eFetchDependencies.REFERENCED // REFERENCED === CHILDREN
1122
+ ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1123
+ : {}), fetchDependencies & eFetchDependencies.REFERENCES // REFERENCES === PARENTS
1124
+ ? C6.TABLES[operatingTable].TABLE_REFERENCES
1125
+ : {});
1126
+ }
1127
+ fetchReferences_1 = {};
1128
+ apiRequestPromises = [];
1129
+ console.log('%c Dependencies', 'color: #005555', dependencies_1);
1130
+ Object.keys(dependencies_1)
1131
+ .forEach(function (column) { return dependencies_1[column]
1132
+ .forEach(function (constraint) {
1133
+ var _a, _b, _c, _d;
1134
+ var _e, _f, _g;
1135
+ var columnValues = (_b = (_a = responseData_1.rest[column]) !== null && _a !== void 0 ? _a : responseData_1.rest.map(function (row) {
1136
+ if (operatingTable.endsWith("carbons")
1137
+ && 'entity_tag' in row
1138
+ && !constraint.TABLE.endsWith(row['entity_tag'].split('\\').pop().toLowerCase())) {
1139
+ return false; // map
1184
1140
  }
1185
- else if (fetchDependencies & eFetchDependencies.C6ENTITY) {
1186
- if (tableToFetch === "carbon_carbons") {
1187
- nextFetchDependencies = fetchDependencies;
1188
- }
1189
- else {
1190
- nextFetchDependencies = fetchDependencies ^ eFetchDependencies.C6ENTITY;
1191
- }
1141
+ if (!(column in row)) {
1142
+ return false;
1192
1143
  }
1193
- console.log('fetchReferences', fetchReferences_1[tableToFetch], "Current fetchDependencies for (" + operatingTable + "):", fetchDependencies, "New fetchDependencies for (" + tableToFetch + "): ", nextFetchDependencies);
1194
- // 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
1195
- // it not certain that they are using carbons' entities either
1196
- // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
1197
- // todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
1198
- apiRequestPromises.push(RestApi.Get((_m = {},
1199
- _m[C6.WHERE] = {
1200
- 0: Object.keys(fetchReferences_1[tableToFetch]).reduce(function (sum, column) {
1201
- fetchReferences_1[tableToFetch][column] = fetchReferences_1[tableToFetch][column].flat(Infinity);
1202
- if (0 === fetchReferences_1[tableToFetch][column].length) {
1203
- console.warn('The column (' + column + ') was not found in the response data. We will not fetch.', responseData_1);
1204
- return false;
1144
+ // todo - row[column] is a FK value, we should optionally remove values that are already in state
1145
+ // this could be any column in the table constraint.TABLE, not just the primary key
1146
+ return row[column];
1147
+ }).filter(function (n) { return n; })) !== null && _b !== void 0 ? _b : [];
1148
+ if (columnValues.length === 0) {
1149
+ return; // forEach
1150
+ }
1151
+ (_c = fetchReferences_1[_e = constraint.TABLE]) !== null && _c !== void 0 ? _c : (fetchReferences_1[_e] = {});
1152
+ (_d = (_f = fetchReferences_1[constraint.TABLE])[_g = constraint.COLUMN]) !== null && _d !== void 0 ? _d : (_f[_g] = []);
1153
+ fetchReferences_1[constraint.TABLE][constraint.COLUMN].push(columnValues);
1154
+ }); });
1155
+ console.log('fetchReferences', fetchReferences_1);
1156
+ _loop_1 = function (tableToFetch) {
1157
+ var referencesTables, shouldContinue, fetchTable, RestApi, nextFetchDependencies;
1158
+ var _m;
1159
+ return __generator(this, function (_o) {
1160
+ switch (_o.label) {
1161
+ case 0:
1162
+ if (fetchDependencies & eFetchDependencies.C6ENTITY
1163
+ && 'string' === typeof tableName
1164
+ && tableName.endsWith("carbon_carbons")) {
1165
+ referencesTables = responseData_1.rest.reduce(function (accumulator, row) {
1166
+ if ('entity_tag' in row && !accumulator.includes(row['entity_tag'])) {
1167
+ accumulator.push(row['entity_tag']);
1168
+ }
1169
+ return accumulator;
1170
+ }, []).map(function (entityTag) { return entityTag.split('\\').pop().toLowerCase(); });
1171
+ shouldContinue = referencesTables.find(function (referencesTable) { return tableToFetch.endsWith(referencesTable); });
1172
+ if (!shouldContinue) {
1173
+ console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables);
1174
+ return [2 /*return*/, "continue"];
1205
1175
  }
1206
- sum[column] = fetchReferences_1[tableToFetch][column].length === 1
1207
- ? fetchReferences_1[tableToFetch][column][0]
1208
- : [
1209
- C6.IN, fetchReferences_1[tableToFetch][column]
1210
- ];
1211
- return sum;
1212
- }, {})
1213
- },
1214
- _m.fetchDependencies = nextFetchDependencies,
1215
- _m)));
1216
- return [2 /*return*/];
1217
- }
1218
- });
1219
- };
1220
- _a = fetchReferences_1;
1221
- _b = [];
1222
- for (_c in _a)
1223
- _b.push(_c);
1224
- _i = 0;
1225
- _l.label = 1;
1226
- case 1:
1227
- if (!(_i < _b.length)) return [3 /*break*/, 4];
1228
- _c = _b[_i];
1229
- if (!(_c in _a)) return [3 /*break*/, 3];
1230
- tableToFetch = _c;
1231
- return [5 /*yield**/, _loop_1(tableToFetch)];
1232
- case 2:
1233
- _l.sent();
1234
- _l.label = 3;
1235
- case 3:
1236
- _i++;
1237
- return [3 /*break*/, 1];
1238
- case 4:
1239
- console.groupEnd();
1240
- return [4 /*yield*/, Promise.all(apiRequestPromises)];
1241
- case 5:
1242
- _l.sent();
1243
- apiRequestPromises.map(function (promise) { return __awaiter(_this, void 0, void 0, function () {
1244
- var _a, _b;
1245
- return __generator(this, function (_c) {
1246
- switch (_c.label) {
1247
- case 0:
1248
- if (!Array.isArray(this.request.fetchDependencies)) {
1249
- // to reassign value we must ref the root
1250
- this.request.fetchDependencies = [];
1176
+ console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') will be fetched.', 'color: #0c0');
1177
+ }
1178
+ return [4 /*yield*/, C6.IMPORT(tableToFetch)];
1179
+ case 1:
1180
+ fetchTable = _o.sent();
1181
+ RestApi = fetchTable.default;
1182
+ console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff');
1183
+ nextFetchDependencies = eFetchDependencies.NONE;
1184
+ if (fetchDependencies & eFetchDependencies.RECURSIVE) {
1185
+ if (fetchDependencies & eFetchDependencies.ALL) {
1186
+ 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.');
1187
+ }
1188
+ nextFetchDependencies = fetchDependencies;
1189
+ }
1190
+ else if (fetchDependencies & eFetchDependencies.C6ENTITY) {
1191
+ if (tableToFetch === "carbon_carbons") {
1192
+ nextFetchDependencies = fetchDependencies;
1193
+ }
1194
+ else {
1195
+ nextFetchDependencies = fetchDependencies ^ eFetchDependencies.C6ENTITY;
1196
+ }
1197
+ }
1198
+ console.log('fetchReferences', fetchReferences_1[tableToFetch], "Current fetchDependencies for (" + operatingTable + "):", fetchDependencies, "New fetchDependencies for (" + tableToFetch + "): ", nextFetchDependencies);
1199
+ // 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
1200
+ // it not certain that they are using carbons' entities either
1201
+ // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
1202
+ // todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
1203
+ apiRequestPromises.push(RestApi.Get((_m = {},
1204
+ _m[C6.WHERE] = {
1205
+ 0: Object.keys(fetchReferences_1[tableToFetch]).reduce(function (sum, column) {
1206
+ fetchReferences_1[tableToFetch][column] = fetchReferences_1[tableToFetch][column].flat(Infinity);
1207
+ if (0 === fetchReferences_1[tableToFetch][column].length) {
1208
+ console.warn('The column (' + column + ') was not found in the response data. We will not fetch.', responseData_1);
1209
+ return false;
1210
+ }
1211
+ sum[column] = fetchReferences_1[tableToFetch][column].length === 1
1212
+ ? fetchReferences_1[tableToFetch][column][0]
1213
+ : [
1214
+ C6.IN, fetchReferences_1[tableToFetch][column]
1215
+ ];
1216
+ return sum;
1217
+ }, {})
1218
+ },
1219
+ _m.fetchDependencies = nextFetchDependencies,
1220
+ _m)));
1221
+ return [2 /*return*/];
1222
+ }
1223
+ });
1224
+ };
1225
+ _a = fetchReferences_1;
1226
+ _b = [];
1227
+ for (_c in _a)
1228
+ _b.push(_c);
1229
+ _i = 0;
1230
+ _l.label = 1;
1231
+ case 1:
1232
+ if (!(_i < _b.length)) return [3 /*break*/, 4];
1233
+ _c = _b[_i];
1234
+ if (!(_c in _a)) return [3 /*break*/, 3];
1235
+ tableToFetch = _c;
1236
+ return [5 /*yield**/, _loop_1(tableToFetch)];
1237
+ case 2:
1238
+ _l.sent();
1239
+ _l.label = 3;
1240
+ case 3:
1241
+ _i++;
1242
+ return [3 /*break*/, 1];
1243
+ case 4:
1244
+ console.groupEnd();
1245
+ return [4 /*yield*/, Promise.all(apiRequestPromises)];
1246
+ case 5:
1247
+ _l.sent();
1248
+ apiRequestPromises.map(function (promise) { return __awaiter(_this, void 0, void 0, function () {
1249
+ var _a, _b;
1250
+ return __generator(this, function (_c) {
1251
+ switch (_c.label) {
1252
+ case 0:
1253
+ if (!Array.isArray(this.request.fetchDependencies)) {
1254
+ // to reassign value we must ref the root
1255
+ this.request.fetchDependencies = [];
1256
+ }
1257
+ _b = (_a = this.request.fetchDependencies).push;
1258
+ return [4 /*yield*/, promise];
1259
+ case 1:
1260
+ _b.apply(_a, [_c.sent()]);
1261
+ return [2 /*return*/];
1251
1262
  }
1252
- _b = (_a = this.request.fetchDependencies).push;
1253
- return [4 /*yield*/, promise];
1254
- case 1:
1255
- _b.apply(_a, [_c.sent()]);
1256
- return [2 /*return*/];
1263
+ });
1264
+ }); });
1265
+ _l.label = 6;
1266
+ case 6:
1267
+ if (debug && isDevelopment) {
1268
+ toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1257
1269
  }
1258
- });
1259
- }); });
1260
- _l.label = 6;
1261
- case 6:
1262
- if (debug && isDevelopment) {
1263
- toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1270
+ return [2 /*return*/, response];
1264
1271
  }
1265
- return [2 /*return*/, response];
1266
- }
1267
- });
1268
- }); })];
1269
- }
1270
- catch (throwableError) {
1271
- if (isTest) {
1272
- throw new Error(JSON.stringify(throwableError));
1273
- }
1274
- console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
1275
- console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
1276
- console.warn(throwableError);
1277
- console.trace();
1278
- console.groupEnd();
1279
- TestRestfulResponse(throwableError, success, error);
1280
- return [2 /*return*/, null];
1272
+ });
1273
+ }); }).then(function (response) { return response.data; })];
1274
+ }
1275
+ catch (throwableError) {
1276
+ if (isTest) {
1277
+ throw new Error(JSON.stringify(throwableError));
1278
+ }
1279
+ console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
1280
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
1281
+ console.warn(throwableError);
1282
+ console.trace();
1283
+ console.groupEnd();
1284
+ TestRestfulResponse(throwableError, success, error);
1285
+ return [2 /*return*/, null];
1286
+ }
1287
+ return [2 /*return*/];
1281
1288
  }
1282
- return [2 /*return*/];
1283
1289
  });
1284
1290
  }); };
1285
1291
  return [4 /*yield*/, apiRequest()];
@@ -1302,17 +1308,43 @@ var SqlExecutor = /** @class */ (function (_super) {
1302
1308
  return _super !== null && _super.apply(this, arguments) || this;
1303
1309
  }
1304
1310
  SqlExecutor.prototype.execute = function () {
1305
- switch (this.config.requestMethod) {
1306
- case 'GET':
1307
- // were about to use this and its fucked
1308
- return this.select(this.config.restModel.TABLE_NAME, undefined, this.request).then(function (rows) { return ({ rest: rows }); });
1309
- case 'POST':
1310
- return this.insert(this.config.restModel.TABLE_NAME, this.request);
1311
- case 'PUT':
1312
- return this.update(this.config.restModel.TABLE_NAME, undefined, this.request);
1313
- case 'DELETE':
1314
- return this.delete(this.config.restModel.TABLE_NAME, undefined, this.request);
1315
- }
1311
+ return __awaiter(this, void 0, void 0, function () {
1312
+ var _a, TABLE_NAME, PRIMARY, _b, rest, result, created, result, updated, result, deleted;
1313
+ return __generator(this, function (_c) {
1314
+ switch (_c.label) {
1315
+ case 0:
1316
+ _a = this.config.restModel, TABLE_NAME = _a.TABLE_NAME, PRIMARY = _a.PRIMARY;
1317
+ _b = this.config.requestMethod;
1318
+ switch (_b) {
1319
+ case 'GET': return [3 /*break*/, 1];
1320
+ case 'POST': return [3 /*break*/, 3];
1321
+ case 'PUT': return [3 /*break*/, 5];
1322
+ case 'DELETE': return [3 /*break*/, 7];
1323
+ }
1324
+ return [3 /*break*/, 9];
1325
+ case 1: return [4 /*yield*/, this.select(TABLE_NAME, undefined, this.request)];
1326
+ case 2:
1327
+ rest = _c.sent();
1328
+ return [2 /*return*/, { rest: rest }];
1329
+ case 3: return [4 /*yield*/, this.insert(TABLE_NAME, this.request)];
1330
+ case 4:
1331
+ result = _c.sent();
1332
+ created = { rest: result, created: true };
1333
+ return [2 /*return*/, created];
1334
+ case 5: return [4 /*yield*/, this.update(TABLE_NAME, PRIMARY, this.request)];
1335
+ case 6:
1336
+ result = _c.sent();
1337
+ updated = { rest: result, updated: true, rowCount: result.affectedRows };
1338
+ return [2 /*return*/, updated];
1339
+ case 7: return [4 /*yield*/, this.delete(TABLE_NAME, PRIMARY, this.request)];
1340
+ case 8:
1341
+ result = _c.sent();
1342
+ deleted = { rest: result, deleted: true, rowCount: result.affectedRows };
1343
+ return [2 /*return*/, deleted];
1344
+ case 9: throw new Error("Unsupported request method: ".concat(this.config.requestMethod));
1345
+ }
1346
+ });
1347
+ });
1316
1348
  };
1317
1349
  SqlExecutor.prototype.withConnection = function (cb) {
1318
1350
  return __awaiter(this, void 0, void 0, function () {
@@ -1395,14 +1427,13 @@ var SqlExecutor = /** @class */ (function (_super) {
1395
1427
  return __generator(this, function (_a) {
1396
1428
  switch (_a.label) {
1397
1429
  case 0:
1398
- if (!primary) {
1430
+ if (!(primary === null || primary === void 0 ? void 0 : primary.length))
1399
1431
  throw new Error('Primary key is required for update');
1400
- }
1401
1432
  keys = Object.keys(data);
1402
1433
  values = keys.map(function (k) { return data[k]; });
1403
1434
  updates = keys.map(function (k) { return "`".concat(k, "` = ?"); }).join(', ');
1404
- sql = "UPDATE `".concat(table, "` SET ").concat(updates, " WHERE `").concat(primary, "` = ?");
1405
- values.push(data[primary]);
1435
+ sql = "UPDATE `".concat(table, "` SET ").concat(updates, " WHERE `").concat(primary[0], "` = ?");
1436
+ values.push(data[primary[0]]);
1406
1437
  return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
1407
1438
  var result;
1408
1439
  return __generator(this, function (_a) {
@@ -1421,20 +1452,20 @@ var SqlExecutor = /** @class */ (function (_super) {
1421
1452
  };
1422
1453
  SqlExecutor.prototype.delete = function (table, primary, args) {
1423
1454
  return __awaiter(this, void 0, void 0, function () {
1424
- var sql;
1455
+ var key, sql;
1425
1456
  var _this = this;
1426
1457
  return __generator(this, function (_a) {
1427
1458
  switch (_a.label) {
1428
1459
  case 0:
1429
- if (!primary || !(args === null || args === void 0 ? void 0 : args[primary])) {
1460
+ key = primary === null || primary === void 0 ? void 0 : primary[0];
1461
+ if (!key || !(args === null || args === void 0 ? void 0 : args[key]))
1430
1462
  throw new Error('Primary key and value required for delete');
1431
- }
1432
- sql = "DELETE FROM `".concat(table, "` WHERE `").concat(primary, "` = ?");
1463
+ sql = "DELETE FROM `".concat(table, "` WHERE `").concat(key, "` = ?");
1433
1464
  return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
1434
1465
  var result;
1435
1466
  return __generator(this, function (_a) {
1436
1467
  switch (_a.label) {
1437
- case 0: return [4 /*yield*/, conn.execute(sql, [args[primary]])];
1468
+ case 0: return [4 /*yield*/, conn.execute(sql, [args[key]])];
1438
1469
  case 1:
1439
1470
  result = (_a.sent())[0];
1440
1471
  return [2 /*return*/, result];
@@ -1498,7 +1529,8 @@ function ExpressHandler(_a) {
1498
1529
  })(payload)];
1499
1530
  case 1:
1500
1531
  response = _a.sent();
1501
- res.status(200).json({ success: true, rest: response });
1532
+ console.log('response', JSON.stringify(response));
1533
+ res.status(200).json(__assign({ success: true }, response));
1502
1534
  return [3 /*break*/, 3];
1503
1535
  case 2:
1504
1536
  err_1 = _a.sent();