@carbonorm/carbonnode 3.0.3 → 3.0.4

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
@@ -1,6 +1,6 @@
1
1
  import axios from 'axios';
2
2
  import Qs from 'qs';
3
- import { __assign, __awaiter, __spreadArray, __generator, __extends } from 'tslib';
3
+ import { __assign, __awaiter, __generator, __extends, __spreadArray } from 'tslib';
4
4
  import { toast } from 'react-toastify';
5
5
 
6
6
  var C6Constants = {
@@ -236,65 +236,70 @@ function convertForRequestBody (restfulObject, tableName, C6, regexErrorHandler)
236
236
  if (regexErrorHandler === void 0) { regexErrorHandler = alert; }
237
237
  var payload = {};
238
238
  var tableNames = Array.isArray(tableName) ? tableName : [tableName];
239
- var tableDefinitions = [];
240
- tableNames.forEach(function (tableName) {
241
- var tableDefinition = Object.values(C6.TABLES).find(function (tableDefinition) { return tableDefinition.TABLE_NAME === tableName; });
242
- if (undefined === tableDefinition) {
243
- console.error("Table name (".concat(tableName, ") is not found in the C6.TABLES object."), C6.TABLES);
244
- throw new Error("Table name (".concat(tableName, ") is not found in the C6.TABLES object."));
239
+ var tableDefinitions = tableNames.map(function (name) {
240
+ var tableDefinition = Object.values(C6.TABLES).find(function (t) { return t.TABLE_NAME === name; });
241
+ if (!tableDefinition) {
242
+ console.error("Table name (".concat(name, ") is not found in the C6.TABLES object."), C6.TABLES);
243
+ throw new Error("Table name (".concat(name, ") is not found in the C6.TABLES object."));
245
244
  }
246
- tableDefinitions.push(tableDefinition);
245
+ return tableDefinition;
247
246
  });
248
- tableDefinitions.forEach(function (tableDefinition) {
249
- Object.keys(restfulObject).forEach(function (value) {
250
- var _a;
247
+ for (var _i = 0, tableDefinitions_1 = tableDefinitions; _i < tableDefinitions_1.length; _i++) {
248
+ var tableDefinition = tableDefinitions_1[_i];
249
+ var _loop_1 = function (value) {
251
250
  var shortReference = value.toUpperCase();
252
- switch (value) {
253
- case C6Constants.GET:
254
- case C6Constants.POST:
255
- case C6Constants.UPDATE:
256
- case C6Constants.REPLACE:
257
- case C6Constants.DELETE:
258
- case C6Constants.WHERE:
259
- case C6Constants.JOIN:
260
- case C6Constants.PAGINATION:
261
- if (Array.isArray(restfulObject[value])) {
262
- payload[value] = restfulObject[value].sort();
263
- }
264
- else if (typeof restfulObject[value] === 'object' && restfulObject[value] !== null) {
265
- payload[value] = Object.keys(restfulObject[value])
266
- .sort()
267
- .reduce(function (acc, key) {
268
- var _a;
269
- return (__assign(__assign({}, acc), (_a = {}, _a[key] = restfulObject[value][key], _a)));
270
- }, {});
271
- }
272
- return;
251
+ if ([
252
+ C6Constants.GET,
253
+ C6Constants.POST,
254
+ C6Constants.UPDATE,
255
+ C6Constants.REPLACE,
256
+ C6Constants.DELETE,
257
+ C6Constants.WHERE,
258
+ C6Constants.JOIN,
259
+ C6Constants.PAGINATION
260
+ ].includes(value)) {
261
+ var val_1 = restfulObject[value];
262
+ if (Array.isArray(val_1)) {
263
+ payload[value] = val_1.sort();
264
+ }
265
+ else if (typeof val_1 === 'object' && val_1 !== null) {
266
+ payload[value] = Object.keys(val_1)
267
+ .sort()
268
+ .reduce(function (acc, key) {
269
+ var _a;
270
+ return (__assign(__assign({}, acc), (_a = {}, _a[key] = val_1[key], _a)));
271
+ }, {});
272
+ }
273
+ return "continue";
273
274
  }
274
275
  if (shortReference in tableDefinition) {
275
- var longName_1 = tableDefinition[shortReference];
276
- payload[longName_1] = restfulObject[value];
277
- var regexValidations_1 = tableDefinition.REGEX_VALIDATION[longName_1];
278
- if (regexValidations_1 instanceof RegExp) {
279
- if (false === regexValidations_1.test(restfulObject[value])) {
280
- regexErrorHandler('Failed to match regex (' + regexValidations_1 + ') for column (' + longName_1 + ')');
281
- throw Error('Failed to match regex (' + regexValidations_1 + ') for column (' + longName_1 + ')');
276
+ var longName = tableDefinition[shortReference];
277
+ var columnValue = restfulObject[value];
278
+ payload[longName] = columnValue;
279
+ var regexValidations = tableDefinition.REGEX_VALIDATION[longName];
280
+ if (regexValidations instanceof RegExp) {
281
+ if (!regexValidations.test(columnValue)) {
282
+ regexErrorHandler("Failed to match regex (".concat(regexValidations, ") for column (").concat(longName, ")"));
283
+ throw new Error("Failed to match regex (".concat(regexValidations, ") for column (").concat(longName, ")"));
282
284
  }
283
285
  }
284
- else if (typeof regexValidations_1 === 'object' && regexValidations_1 !== null) {
285
- (_a = Object.keys(regexValidations_1)) === null || _a === void 0 ? void 0 : _a.forEach(function (errorMessage) {
286
- var regex = regexValidations_1[errorMessage];
287
- if (false === regex.test(restfulObject[value])) {
288
- var devErrorMessage = 'Failed to match regex (' + regex + ') for column (' + longName_1 + ')';
289
- regexErrorHandler(errorMessage !== null && errorMessage !== void 0 ? errorMessage : devErrorMessage);
290
- throw Error(devErrorMessage);
286
+ else if (typeof regexValidations === 'object' && regexValidations !== null) {
287
+ for (var errorMessage in regexValidations) {
288
+ var regex = regexValidations[errorMessage];
289
+ if (!regex.test(columnValue)) {
290
+ var devErrorMessage = "Failed to match regex (".concat(regex, ") for column (").concat(longName, ")");
291
+ regexErrorHandler(errorMessage || devErrorMessage);
292
+ throw new Error(devErrorMessage);
291
293
  }
292
- });
294
+ }
293
295
  }
294
296
  }
295
- });
296
- return true;
297
- });
297
+ };
298
+ for (var _a = 0, _b = Object.keys(restfulObject); _a < _b.length; _a++) {
299
+ var value = _b[_a];
300
+ _loop_1(value);
301
+ }
302
+ }
298
303
  return Object.keys(payload)
299
304
  .sort()
300
305
  .reduce(function (acc, key) {
@@ -311,32 +316,25 @@ var isNode = typeof process !== 'undefined' && !!((_a = process.versions) === nu
311
316
  */
312
317
  function restRequest(config) {
313
318
  var _this = this;
314
- return function () {
315
- var args_1 = [];
316
- for (var _i = 0; _i < arguments.length; _i++) {
317
- args_1[_i] = arguments[_i];
318
- }
319
- return __awaiter(_this, __spreadArray([], args_1, true), void 0, function (request) {
320
- var SqlExecutor, executor, HttpExecutor, http;
321
- if (request === void 0) { request = {}; }
322
- return __generator(this, function (_a) {
323
- switch (_a.label) {
324
- case 0:
325
- if (!(isNode && config.mysqlPool)) return [3 /*break*/, 2];
326
- return [4 /*yield*/, Promise.resolve().then(function () { return SqlExecutor$1; })];
327
- case 1:
328
- SqlExecutor = (_a.sent()).SqlExecutor;
329
- executor = new SqlExecutor(config, request);
330
- return [2 /*return*/, executor.execute()];
331
- case 2: return [4 /*yield*/, Promise.resolve().then(function () { return HttpExecutor$1; })];
332
- case 3:
333
- HttpExecutor = (_a.sent()).HttpExecutor;
334
- http = new HttpExecutor(config, request);
335
- return [2 /*return*/, http.execute()];
336
- }
337
- });
319
+ return function (request) { return __awaiter(_this, void 0, void 0, function () {
320
+ var SqlExecutor, executor, HttpExecutor, http;
321
+ return __generator(this, function (_a) {
322
+ switch (_a.label) {
323
+ case 0:
324
+ if (!(isNode && config.mysqlPool)) return [3 /*break*/, 2];
325
+ return [4 /*yield*/, Promise.resolve().then(function () { return SqlExecutor$1; })];
326
+ case 1:
327
+ SqlExecutor = (_a.sent()).SqlExecutor;
328
+ executor = new SqlExecutor(config, request);
329
+ return [2 /*return*/, executor.execute()];
330
+ case 2: return [4 /*yield*/, Promise.resolve().then(function () { return HttpExecutor$1; })];
331
+ case 3:
332
+ HttpExecutor = (_a.sent()).HttpExecutor;
333
+ http = new HttpExecutor(config, request);
334
+ return [2 /*return*/, http.execute()];
335
+ }
338
336
  });
339
- };
337
+ }); };
340
338
  }
341
339
 
342
340
  function restOrm(config) {
@@ -541,7 +539,6 @@ var isVerbose = ['true', '1', 'yes', 'on'].includes(envVerbose.toLowerCase());
541
539
 
542
540
  var Executor = /** @class */ (function () {
543
541
  function Executor(config, request) {
544
- if (request === void 0) { request = {}; }
545
542
  this.config = config;
546
543
  this.request = request;
547
544
  }
@@ -610,23 +607,11 @@ var eFetchDependencies;
610
607
  eFetchDependencies[eFetchDependencies["RECURSIVE"] = 8] = "RECURSIVE";
611
608
  })(eFetchDependencies || (eFetchDependencies = {}));
612
609
 
613
- /**
614
- * the first argument ....
615
- *
616
- * Our api returns a zero argument function iff the method is get and the previous request reached the predefined limit.
617
- * This function can be aliased as GetNextPageOfResults(). If the end is reached undefined will be returned.
618
- *
619
- *
620
- * For POST, PUT, and DELETE requests one can expect the primary key of the new or modified index, or a boolean success
621
- * indication if no primary key exists.
622
- **/
610
+ // Refined TypeScript types for CarbonORM
623
611
  var POST = 'POST';
624
612
  var PUT = 'PUT';
625
613
  var GET = 'GET';
626
614
  var DELETE = 'DELETE';
627
- function isPromise(x) {
628
- return Object(x).constructor === Promise;
629
- }
630
615
 
631
616
  var toastOptions = {
632
617
  position: "bottom-left",
@@ -788,11 +773,12 @@ var HttpExecutor = /** @class */ (function (_super) {
788
773
  };
789
774
  HttpExecutor.prototype.execute = function () {
790
775
  return __awaiter(this, void 0, void 0, function () {
791
- var _a, C6, restModel, requestMethod, clearCache, tableName, fullTableList, operatingTableFullName, tables;
776
+ var _a, C6, axios, restURL, withCredentials, restModel, reactBootstrap, requestMethod, skipPrimaryCheck, clearCache, tableName, fullTableList, operatingTableFullName, operatingTable, tables, query, apiRequest;
777
+ var _this = this;
792
778
  return __generator(this, function (_b) {
793
779
  switch (_b.label) {
794
780
  case 0:
795
- _a = this.config, C6 = _a.C6, _a.axios, _a.restURL, _a.withCredentials, restModel = _a.restModel, _a.reactBootstrap, requestMethod = _a.requestMethod, _a.skipPrimaryCheck, clearCache = _a.clearCache;
781
+ _a = this.config, C6 = _a.C6, axios = _a.axios, restURL = _a.restURL, withCredentials = _a.withCredentials, restModel = _a.restModel, reactBootstrap = _a.reactBootstrap, requestMethod = _a.requestMethod, skipPrimaryCheck = _a.skipPrimaryCheck, clearCache = _a.clearCache;
796
782
  return [4 /*yield*/, this.runLifecycleHooks("beforeProcessing", {
797
783
  config: this.config,
798
784
  request: this.request,
@@ -802,7 +788,7 @@ var HttpExecutor = /** @class */ (function (_super) {
802
788
  tableName = restModel.TABLE_NAME;
803
789
  fullTableList = Array.isArray(tableName) ? tableName : [tableName];
804
790
  operatingTableFullName = fullTableList[0];
805
- removePrefixIfExists(operatingTableFullName, C6.PREFIX);
791
+ operatingTable = removePrefixIfExists(operatingTableFullName, C6.PREFIX);
806
792
  tables = fullTableList.join(',');
807
793
  switch (requestMethod) {
808
794
  case GET:
@@ -819,16 +805,482 @@ var HttpExecutor = /** @class */ (function (_super) {
819
805
  console.groupCollapsed('%c API: (' + requestMethod + ') Request for (' + tableName + ')', 'color: #0c0');
820
806
  console.log('request', this.request);
821
807
  console.groupEnd();
822
- {
823
- if (this.request.debug && isDevelopment) {
824
- toast.warning("DEV: queryCallback returned undefined, signaling in Custom Cache. (returning null)", toastOptionsDevs);
825
- }
826
- console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + tableName + ') undefined, returning null (will not fire ajax)!', 'color: #c00');
808
+ // an undefined query would indicate queryCallback returned undefined,
809
+ // thus the request shouldn't fire as is in custom cache
810
+ if (undefined === this.request || null === this.request) {
811
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + tableName + ') undefined, returning null (will not fire)!', 'color: #c00');
827
812
  console.log('%c Returning (undefined|null) for a query would indicate a custom cache hit (outside API.tsx), thus the request should not fire.', 'color: #c00');
828
813
  console.trace();
829
814
  console.groupEnd();
830
815
  return [2 /*return*/, null];
831
816
  }
817
+ query = this.request;
818
+ if (C6.GET === requestMethod) {
819
+ if (undefined === query[C6.PAGINATION]) {
820
+ query[C6.PAGINATION] = {};
821
+ }
822
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
823
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
824
+ }
825
+ apiRequest = function () { return __awaiter(_this, void 0, void 0, function () {
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;
827
+ var _e;
828
+ var _this = this;
829
+ var _f, _g, _h, _j, _k, _l;
830
+ return __generator(this, function (_m) {
831
+ _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;
832
+ if (C6.GET === requestMethod
833
+ && undefined !== ((_f = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _f === void 0 ? void 0 : _f[C6.PAGE])
834
+ && 1 !== query[C6.PAGINATION][C6.PAGE]) {
835
+ console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
836
+ console.log('Request Data (note you may see the success and/or error prompt):', this.request);
837
+ console.trace();
838
+ console.groupEnd();
839
+ }
840
+ querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
841
+ cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
842
+ cachingConfirmed = false;
843
+ // determine if we need to paginate.
844
+ if (requestMethod === C6.GET) {
845
+ if (undefined === (query === null || query === void 0 ? void 0 : query[C6.PAGINATION])) {
846
+ if (undefined === query || null === query) {
847
+ query = {};
848
+ }
849
+ query[C6.PAGINATION] = {};
850
+ }
851
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
852
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
853
+ // this will evaluate true most the time
854
+ if (true === cacheResults) {
855
+ // just find the next, non-fetched, page and return a function to request it
856
+ if (undefined !== cacheResult) {
857
+ do {
858
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
859
+ if (false !== cacheCheck) {
860
+ return [2 /*return*/, cacheCheck];
861
+ }
862
+ // this line incrementing page is why we return recursively
863
+ ++query[C6.PAGINATION][C6.PAGE];
864
+ // this json stringify is to capture the new page number
865
+ querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
866
+ cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
867
+ } while (undefined !== cacheResult);
868
+ if (debug && isDevelopment) {
869
+ 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);
870
+ }
871
+ // @ts-ignore - this is an incorrect warning on TS, it's well typed
872
+ return [2 /*return*/, apiRequest];
873
+ }
874
+ cachingConfirmed = true;
875
+ }
876
+ else {
877
+ if (debug && isDevelopment) {
878
+ toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
879
+ }
880
+ }
881
+ if (debug && isDevelopment) {
882
+ toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
883
+ }
884
+ }
885
+ else if (cacheResults) { // if we are not getting, we are updating, deleting, or inserting
886
+ if (cacheResult) {
887
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
888
+ if (false !== cacheCheck) {
889
+ return [2 /*return*/, cacheCheck];
890
+ }
891
+ }
892
+ cachingConfirmed = true;
893
+ // push to cache so we do not repeat the request
894
+ }
895
+ returnGetNextPageFunction = false;
896
+ restRequestUri = restURL + operatingTable + '/';
897
+ needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
898
+ && false === skipPrimaryCheck;
899
+ TABLES = C6.TABLES;
900
+ 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();
901
+ if (needsConditionOrPrimaryCheck) {
902
+ if (undefined === primaryKey) {
903
+ if (null === query
904
+ || undefined === query
905
+ || undefined === (query === null || query === void 0 ? void 0 : query[C6.WHERE])
906
+ || (true === Array.isArray(query[C6.WHERE])
907
+ || query[C6.WHERE].length === 0)
908
+ || (Object.keys(query === null || query === void 0 ? void 0 : query[C6.WHERE]).length === 0)) {
909
+ console.error(query);
910
+ 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 + ').');
911
+ }
912
+ }
913
+ else {
914
+ if (undefined === query
915
+ || null === query
916
+ || false === primaryKey in query) {
917
+ if (true === debug && isDevelopment) {
918
+ toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
919
+ }
920
+ throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(this.request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
921
+ }
922
+ if (undefined === (query === null || query === void 0 ? void 0 : query[primaryKey])
923
+ || null === (query === null || query === void 0 ? void 0 : query[primaryKey])) {
924
+ toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!');
925
+ throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
926
+ }
927
+ }
928
+ }
929
+ // A part of me exists that wants to remove this, but it's a good feature
930
+ // this allows developers the ability to cache requests based on primary key
931
+ // for tables like `photos` this can be a huge performance boost
932
+ if (undefined !== query
933
+ && null !== query
934
+ && undefined !== primaryKey
935
+ && primaryKey in query) {
936
+ restRequestUri += query[primaryKey] + '/';
937
+ removedPkValue_1 = query[primaryKey];
938
+ addBackPK = function () {
939
+ query !== null && query !== void 0 ? query : (query = {});
940
+ query[primaryKey] = removedPkValue_1;
941
+ };
942
+ delete query[primaryKey];
943
+ console.log('query', query, 'primaryKey', primaryKey, 'removedPkValue', removedPkValue_1);
944
+ }
945
+ else {
946
+ console.log('query', query);
947
+ }
948
+ try {
949
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
950
+ console.log(this.request);
951
+ 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');
952
+ 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');
953
+ console.trace();
954
+ console.groupEnd();
955
+ this.runLifecycleHooks("beforeExecution", {
956
+ config: this.config,
957
+ request: this.request
958
+ });
959
+ axiosActiveRequest = (_e = axios)[requestMethod.toLowerCase()].apply(_e, __spreadArray([restRequestUri], (function () {
960
+ var convert = function (data) {
961
+ return convertForRequestBody(data, fullTableList, C6, function (message) { return toast.error(message, toastOptions); });
962
+ };
963
+ var baseConfig = {
964
+ withCredentials: withCredentials,
965
+ };
966
+ switch (requestMethod) {
967
+ case GET:
968
+ return [__assign(__assign({}, baseConfig), { params: query })];
969
+ case POST:
970
+ if (dataInsertMultipleRows !== undefined) {
971
+ return [
972
+ dataInsertMultipleRows.map(convert),
973
+ baseConfig
974
+ ];
975
+ }
976
+ return [convert(query), baseConfig];
977
+ case PUT:
978
+ return [convert(query), baseConfig];
979
+ case DELETE:
980
+ return [__assign(__assign({}, baseConfig), { data: convert(query) })];
981
+ default:
982
+ throw new Error("The request method (".concat(requestMethod, ") was not recognized."));
983
+ }
984
+ })(), false));
985
+ if (cachingConfirmed) {
986
+ // push to cache so we do not repeat the request
987
+ apiRequestCache.push({
988
+ requestArgumentsSerialized: querySerialized,
989
+ request: axiosActiveRequest
990
+ });
991
+ }
992
+ // todo - wip verify this works
993
+ // we had removed the value from the request to add to the URI.
994
+ addBackPK === null || addBackPK === void 0 ? void 0 : addBackPK(); // adding back so post-processing methods work
995
+ // returning the promise with this then is important for tests. todo - we could make that optional.
996
+ // https://rapidapi.com/guides/axios-async-await
997
+ return [2 /*return*/, axiosActiveRequest.then(function (response) { return __awaiter(_this, void 0, void 0, function () {
998
+ var cacheIndex, callback, responseData_1, dependencies_1, fetchReferences_1, apiRequestPromises, _loop_1, _a, _b, _c, _i, tableToFetch;
999
+ var _this = this;
1000
+ var _d, _e, _f, _g, _h, _j, _k;
1001
+ return __generator(this, function (_l) {
1002
+ switch (_l.label) {
1003
+ case 0:
1004
+ // noinspection SuspiciousTypeOfGuard
1005
+ if (typeof response.data === 'string') {
1006
+ if (isTest) {
1007
+ console.trace();
1008
+ 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 + ')');
1009
+ }
1010
+ return [2 /*return*/, Promise.reject(response)];
1011
+ }
1012
+ if (cachingConfirmed) {
1013
+ cacheIndex = apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
1014
+ apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction;
1015
+ // only cache get method requests
1016
+ apiRequestCache[cacheIndex].response = response;
1017
+ }
1018
+ this.runLifecycleHooks("afterExecution", {
1019
+ config: this.config,
1020
+ request: this.request,
1021
+ response: response
1022
+ });
1023
+ // todo - this feels dumb now, but i digress
1024
+ apiResponse = TestRestfulResponse(response, success, error);
1025
+ if (false === apiResponse) {
1026
+ if (debug && isDevelopment) {
1027
+ toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
1028
+ }
1029
+ return [2 /*return*/, response];
1030
+ }
1031
+ callback = function () { return _this.runLifecycleHooks("afterCommit", {
1032
+ config: _this.config,
1033
+ request: _this.request,
1034
+ response: response
1035
+ }); };
1036
+ if (undefined !== reactBootstrap && response) {
1037
+ switch (requestMethod) {
1038
+ case GET:
1039
+ reactBootstrap.updateRestfulObjectArrays({
1040
+ dataOrCallback: Array.isArray(response.data.rest) ? response.data.rest : [response.data.rest],
1041
+ stateKey: this.config.restModel.TABLE_NAME,
1042
+ uniqueObjectId: this.config.restModel.PRIMARY_SHORT,
1043
+ callback: callback
1044
+ });
1045
+ break;
1046
+ case POST:
1047
+ this.postState(response, this.request, callback);
1048
+ break;
1049
+ case PUT:
1050
+ this.putState(response, this.request, callback);
1051
+ break;
1052
+ case DELETE:
1053
+ this.deleteState(response, this.request, callback);
1054
+ break;
1055
+ }
1056
+ }
1057
+ else {
1058
+ callback();
1059
+ }
1060
+ if (!(C6.GET === requestMethod)) return [3 /*break*/, 6];
1061
+ responseData_1 = response.data;
1062
+ returnGetNextPageFunction = 1 !== ((_d = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _d === void 0 ? void 0 : _d[C6.LIMIT]) &&
1063
+ ((_e = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _e === void 0 ? void 0 : _e[C6.LIMIT]) === responseData_1.rest.length;
1064
+ if (false === isTest || true === isVerbose) {
1065
+ 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');
1066
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
1067
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', this.request);
1068
+ console.log('%c Response Data:', 'color: #0c0', responseData_1.rest);
1069
+ 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);
1070
+ console.trace();
1071
+ console.groupEnd();
1072
+ }
1073
+ if (false === returnGetNextPageFunction
1074
+ && true === debug
1075
+ && isDevelopment) {
1076
+ 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);
1077
+ }
1078
+ if (!(fetchDependencies
1079
+ && 'number' === typeof fetchDependencies
1080
+ && responseData_1.rest.length > 0)) return [3 /*break*/, 6];
1081
+ console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
1082
+ + (fetchDependencies & eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
1083
+ + (fetchDependencies & eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
1084
+ + (fetchDependencies & eFetchDependencies.C6ENTITY ? ' | (C6ENTITY)' : '')
1085
+ + (fetchDependencies & eFetchDependencies.RECURSIVE ? ' | (RECURSIVE)' : ''), 'color: #33ccff');
1086
+ console.groupCollapsed('Collapsed JS Trace');
1087
+ console.trace(); // hidden in collapsed group
1088
+ console.groupEnd();
1089
+ dependencies_1 = {};
1090
+ if (fetchDependencies & eFetchDependencies.C6ENTITY) {
1091
+ dependencies_1 = operatingTable.endsWith("carbon_carbons")
1092
+ ? __assign(__assign({}, fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
1093
+ ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1094
+ : {}), fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
1095
+ ? C6.TABLES[operatingTable].TABLE_REFERENCES
1096
+ : {}) : __assign(__assign({}, fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
1097
+ ? __assign(__assign({}, Object.keys(C6.TABLES[operatingTable].TABLE_REFERENCES).reduce(function (accumulator, columnName) {
1098
+ if (!C6.TABLES[operatingTable].PRIMARY_SHORT.includes(columnName)) {
1099
+ accumulator[columnName] = C6.TABLES[operatingTable].TABLE_REFERENCES[columnName];
1100
+ }
1101
+ return accumulator;
1102
+ }, {})), C6.TABLES[operatingTable].TABLE_REFERENCED_BY // it is unlikely that a C6 table will have any TABLE_REFERENCED_BY
1103
+ ) : {}), fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
1104
+ ? C6.TABLES[operatingTable].PRIMARY_SHORT.reduce(function (accumulator, primaryKey) {
1105
+ if (primaryKey in C6.TABLES[operatingTable].TABLE_REFERENCES) {
1106
+ accumulator[primaryKey] = C6.TABLES[operatingTable].TABLE_REFERENCES[primaryKey];
1107
+ }
1108
+ return accumulator;
1109
+ }, {})
1110
+ : {});
1111
+ }
1112
+ else {
1113
+ // this is the natural mysql context
1114
+ dependencies_1 = __assign(__assign({}, fetchDependencies & eFetchDependencies.REFERENCED // REFERENCED === CHILDREN
1115
+ ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1116
+ : {}), fetchDependencies & eFetchDependencies.REFERENCES // REFERENCES === PARENTS
1117
+ ? C6.TABLES[operatingTable].TABLE_REFERENCES
1118
+ : {});
1119
+ }
1120
+ fetchReferences_1 = {};
1121
+ apiRequestPromises = [];
1122
+ console.log('%c Dependencies', 'color: #005555', dependencies_1);
1123
+ Object.keys(dependencies_1)
1124
+ .forEach(function (column) { return dependencies_1[column]
1125
+ .forEach(function (constraint) {
1126
+ var _a, _b, _c, _d;
1127
+ var _e, _f, _g;
1128
+ var columnValues = (_b = (_a = responseData_1.rest[column]) !== null && _a !== void 0 ? _a : responseData_1.rest.map(function (row) {
1129
+ if (operatingTable.endsWith("carbons")
1130
+ && 'entity_tag' in row
1131
+ && !constraint.TABLE.endsWith(row['entity_tag'].split('\\').pop().toLowerCase())) {
1132
+ return false; // map
1133
+ }
1134
+ if (!(column in row)) {
1135
+ return false;
1136
+ }
1137
+ // todo - row[column] is a FK value, we should optionally remove values that are already in state
1138
+ // this could be any column in the table constraint.TABLE, not just the primary key
1139
+ return row[column];
1140
+ }).filter(function (n) { return n; })) !== null && _b !== void 0 ? _b : [];
1141
+ if (columnValues.length === 0) {
1142
+ return; // forEach
1143
+ }
1144
+ (_c = fetchReferences_1[_e = constraint.TABLE]) !== null && _c !== void 0 ? _c : (fetchReferences_1[_e] = {});
1145
+ (_d = (_f = fetchReferences_1[constraint.TABLE])[_g = constraint.COLUMN]) !== null && _d !== void 0 ? _d : (_f[_g] = []);
1146
+ fetchReferences_1[constraint.TABLE][constraint.COLUMN].push(columnValues);
1147
+ }); });
1148
+ console.log('fetchReferences', fetchReferences_1);
1149
+ _loop_1 = function (tableToFetch) {
1150
+ var referencesTables, shouldContinue, fetchTable, RestApi, nextFetchDependencies;
1151
+ var _m;
1152
+ return __generator(this, function (_o) {
1153
+ switch (_o.label) {
1154
+ case 0:
1155
+ if (fetchDependencies & eFetchDependencies.C6ENTITY
1156
+ && 'string' === typeof tableName
1157
+ && tableName.endsWith("carbon_carbons")) {
1158
+ referencesTables = responseData_1.rest.reduce(function (accumulator, row) {
1159
+ if ('entity_tag' in row && !accumulator.includes(row['entity_tag'])) {
1160
+ accumulator.push(row['entity_tag']);
1161
+ }
1162
+ return accumulator;
1163
+ }, []).map(function (entityTag) { return entityTag.split('\\').pop().toLowerCase(); });
1164
+ shouldContinue = referencesTables.find(function (referencesTable) { return tableToFetch.endsWith(referencesTable); });
1165
+ if (!shouldContinue) {
1166
+ console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables);
1167
+ return [2 /*return*/, "continue"];
1168
+ }
1169
+ console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') will be fetched.', 'color: #0c0');
1170
+ }
1171
+ return [4 /*yield*/, C6.IMPORT(tableToFetch)];
1172
+ case 1:
1173
+ fetchTable = _o.sent();
1174
+ RestApi = fetchTable.default;
1175
+ console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff');
1176
+ nextFetchDependencies = eFetchDependencies.NONE;
1177
+ if (fetchDependencies & eFetchDependencies.RECURSIVE) {
1178
+ if (fetchDependencies & eFetchDependencies.ALL) {
1179
+ 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.');
1180
+ }
1181
+ nextFetchDependencies = fetchDependencies;
1182
+ }
1183
+ else if (fetchDependencies & eFetchDependencies.C6ENTITY) {
1184
+ if (tableToFetch === "carbon_carbons") {
1185
+ nextFetchDependencies = fetchDependencies;
1186
+ }
1187
+ else {
1188
+ nextFetchDependencies = fetchDependencies ^ eFetchDependencies.C6ENTITY;
1189
+ }
1190
+ }
1191
+ console.log('fetchReferences', fetchReferences_1[tableToFetch], "Current fetchDependencies for (" + operatingTable + "):", fetchDependencies, "New fetchDependencies for (" + tableToFetch + "): ", nextFetchDependencies);
1192
+ // 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
1193
+ // it not certain that they are using carbons' entities either
1194
+ // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
1195
+ // todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
1196
+ apiRequestPromises.push(RestApi.Get((_m = {},
1197
+ _m[C6.WHERE] = {
1198
+ 0: Object.keys(fetchReferences_1[tableToFetch]).reduce(function (sum, column) {
1199
+ fetchReferences_1[tableToFetch][column] = fetchReferences_1[tableToFetch][column].flat(Infinity);
1200
+ if (0 === fetchReferences_1[tableToFetch][column].length) {
1201
+ console.warn('The column (' + column + ') was not found in the response data. We will not fetch.', responseData_1);
1202
+ return false;
1203
+ }
1204
+ sum[column] = fetchReferences_1[tableToFetch][column].length === 1
1205
+ ? fetchReferences_1[tableToFetch][column][0]
1206
+ : [
1207
+ C6.IN, fetchReferences_1[tableToFetch][column]
1208
+ ];
1209
+ return sum;
1210
+ }, {})
1211
+ },
1212
+ _m.fetchDependencies = nextFetchDependencies,
1213
+ _m)));
1214
+ return [2 /*return*/];
1215
+ }
1216
+ });
1217
+ };
1218
+ _a = fetchReferences_1;
1219
+ _b = [];
1220
+ for (_c in _a)
1221
+ _b.push(_c);
1222
+ _i = 0;
1223
+ _l.label = 1;
1224
+ case 1:
1225
+ if (!(_i < _b.length)) return [3 /*break*/, 4];
1226
+ _c = _b[_i];
1227
+ if (!(_c in _a)) return [3 /*break*/, 3];
1228
+ tableToFetch = _c;
1229
+ return [5 /*yield**/, _loop_1(tableToFetch)];
1230
+ case 2:
1231
+ _l.sent();
1232
+ _l.label = 3;
1233
+ case 3:
1234
+ _i++;
1235
+ return [3 /*break*/, 1];
1236
+ case 4:
1237
+ console.groupEnd();
1238
+ return [4 /*yield*/, Promise.all(apiRequestPromises)];
1239
+ case 5:
1240
+ _l.sent();
1241
+ apiRequestPromises.map(function (promise) { return __awaiter(_this, void 0, void 0, function () {
1242
+ var _a, _b;
1243
+ return __generator(this, function (_c) {
1244
+ switch (_c.label) {
1245
+ case 0:
1246
+ if (!Array.isArray(this.request.fetchDependencies)) {
1247
+ // to reassign value we must ref the root
1248
+ this.request.fetchDependencies = [];
1249
+ }
1250
+ _b = (_a = this.request.fetchDependencies).push;
1251
+ return [4 /*yield*/, promise];
1252
+ case 1:
1253
+ _b.apply(_a, [_c.sent()]);
1254
+ return [2 /*return*/];
1255
+ }
1256
+ });
1257
+ }); });
1258
+ _l.label = 6;
1259
+ case 6:
1260
+ if (debug && isDevelopment) {
1261
+ toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1262
+ }
1263
+ return [2 /*return*/, response];
1264
+ }
1265
+ });
1266
+ }); })];
1267
+ }
1268
+ catch (throwableError) {
1269
+ if (isTest) {
1270
+ throw new Error(JSON.stringify(throwableError));
1271
+ }
1272
+ console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
1273
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
1274
+ console.warn(throwableError);
1275
+ console.trace();
1276
+ console.groupEnd();
1277
+ TestRestfulResponse(throwableError, success, error);
1278
+ return [2 /*return*/, null];
1279
+ }
1280
+ return [2 /*return*/];
1281
+ });
1282
+ }); };
1283
+ return [4 /*yield*/, apiRequest()];
832
1284
  case 2: return [2 /*return*/, _b.sent()];
833
1285
  }
834
1286
  });
@@ -1097,5 +1549,5 @@ function onError(message) {
1097
1549
  toast.error(message, isDevelopment ? toastOptionsDevs : toastOptions);
1098
1550
  }
1099
1551
 
1100
- export { C6Constants, DELETE, Executor, GET, HttpExecutor, POST, PUT, SqlExecutor, TestRestfulResponse, apiRequestCache, axiosInstance, buildAggregateField, buildBooleanJoinedConditions, buildSelectQuery, checkAllRequestsComplete, checkCache, clearCache, convertForRequestBody, determineRuntimeJsType, eFetchDependencies, error, getEnvVar, getPrimaryKeyTypes, group, info, isDevelopment as isLocal, isNode, isPromise, isTest, isVerbose, onError, onSuccess, removeInvalidKeys, removePrefixIfExists, restOrm, restRequest, sortAndSerializeQueryObject, timeout, toastOptions, toastOptionsDevs, userCustomClearCache, warn };
1552
+ export { C6Constants, DELETE, Executor, GET, HttpExecutor, POST, PUT, SqlExecutor, TestRestfulResponse, apiRequestCache, axiosInstance, buildAggregateField, buildBooleanJoinedConditions, buildSelectQuery, checkAllRequestsComplete, checkCache, clearCache, convertForRequestBody, determineRuntimeJsType, eFetchDependencies, error, getEnvVar, getPrimaryKeyTypes, group, info, isDevelopment as isLocal, isNode, isTest, isVerbose, onError, onSuccess, removeInvalidKeys, removePrefixIfExists, restOrm, restRequest, sortAndSerializeQueryObject, timeout, toastOptions, toastOptionsDevs, userCustomClearCache, warn };
1101
1553
  //# sourceMappingURL=index.esm.js.map