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