@carbonorm/carbonnode 3.0.3 → 3.0.5

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,483 @@ 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');
815
+ console.log('request', this.request);
830
816
  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
817
  console.trace();
832
818
  console.groupEnd();
833
819
  return [2 /*return*/, null];
834
820
  }
821
+ query = this.request;
822
+ if (C6.GET === requestMethod) {
823
+ if (undefined === query[C6.PAGINATION]) {
824
+ query[C6.PAGINATION] = {};
825
+ }
826
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
827
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
828
+ }
829
+ apiRequest = function () { return tslib.__awaiter(_this, void 0, void 0, function () {
830
+ 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;
831
+ var _e;
832
+ var _this = this;
833
+ var _f, _g, _h, _j, _k, _l;
834
+ return tslib.__generator(this, function (_m) {
835
+ _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;
836
+ if (C6.GET === requestMethod
837
+ && undefined !== ((_f = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _f === void 0 ? void 0 : _f[C6.PAGE])
838
+ && 1 !== query[C6.PAGINATION][C6.PAGE]) {
839
+ console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
840
+ console.log('Request Data (note you may see the success and/or error prompt):', this.request);
841
+ console.trace();
842
+ console.groupEnd();
843
+ }
844
+ querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
845
+ cacheResult = exports.apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
846
+ cachingConfirmed = false;
847
+ // determine if we need to paginate.
848
+ if (requestMethod === C6.GET) {
849
+ if (undefined === (query === null || query === void 0 ? void 0 : query[C6.PAGINATION])) {
850
+ if (undefined === query || null === query) {
851
+ query = {};
852
+ }
853
+ query[C6.PAGINATION] = {};
854
+ }
855
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
856
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
857
+ // this will evaluate true most the time
858
+ if (true === cacheResults) {
859
+ // just find the next, non-fetched, page and return a function to request it
860
+ if (undefined !== cacheResult) {
861
+ do {
862
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
863
+ if (false !== cacheCheck) {
864
+ return [2 /*return*/, cacheCheck];
865
+ }
866
+ // this line incrementing page is why we return recursively
867
+ ++query[C6.PAGINATION][C6.PAGE];
868
+ // this json stringify is to capture the new page number
869
+ querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
870
+ cacheResult = exports.apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
871
+ } while (undefined !== cacheResult);
872
+ if (debug && isDevelopment) {
873
+ 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);
874
+ }
875
+ // @ts-ignore - this is an incorrect warning on TS, it's well typed
876
+ return [2 /*return*/, apiRequest];
877
+ }
878
+ cachingConfirmed = true;
879
+ }
880
+ else {
881
+ if (debug && isDevelopment) {
882
+ reactToastify.toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
883
+ }
884
+ }
885
+ if (debug && isDevelopment) {
886
+ reactToastify.toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
887
+ }
888
+ }
889
+ else if (cacheResults) { // if we are not getting, we are updating, deleting, or inserting
890
+ if (cacheResult) {
891
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
892
+ if (false !== cacheCheck) {
893
+ return [2 /*return*/, cacheCheck];
894
+ }
895
+ }
896
+ cachingConfirmed = true;
897
+ // push to cache so we do not repeat the request
898
+ }
899
+ returnGetNextPageFunction = false;
900
+ restRequestUri = restURL + operatingTable + '/';
901
+ needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
902
+ && false === skipPrimaryCheck;
903
+ TABLES = C6.TABLES;
904
+ 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();
905
+ if (needsConditionOrPrimaryCheck) {
906
+ if (undefined === primaryKey) {
907
+ if (null === query
908
+ || undefined === query
909
+ || undefined === (query === null || query === void 0 ? void 0 : query[C6.WHERE])
910
+ || (true === Array.isArray(query[C6.WHERE])
911
+ || query[C6.WHERE].length === 0)
912
+ || (Object.keys(query === null || query === void 0 ? void 0 : query[C6.WHERE]).length === 0)) {
913
+ console.error(query);
914
+ 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 + ').');
915
+ }
916
+ }
917
+ else {
918
+ if (undefined === query
919
+ || null === query
920
+ || false === primaryKey in query) {
921
+ if (true === debug && isDevelopment) {
922
+ reactToastify.toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
923
+ }
924
+ throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(this.request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
925
+ }
926
+ if (undefined === (query === null || query === void 0 ? void 0 : query[primaryKey])
927
+ || null === (query === null || query === void 0 ? void 0 : query[primaryKey])) {
928
+ reactToastify.toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!');
929
+ throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
930
+ }
931
+ }
932
+ }
933
+ // A part of me exists that wants to remove this, but it's a good feature
934
+ // this allows developers the ability to cache requests based on primary key
935
+ // for tables like `photos` this can be a huge performance boost
936
+ if (undefined !== query
937
+ && null !== query
938
+ && undefined !== primaryKey
939
+ && primaryKey in query) {
940
+ restRequestUri += query[primaryKey] + '/';
941
+ removedPkValue_1 = query[primaryKey];
942
+ addBackPK = function () {
943
+ query !== null && query !== void 0 ? query : (query = {});
944
+ query[primaryKey] = removedPkValue_1;
945
+ };
946
+ delete query[primaryKey];
947
+ console.log('query', query, 'primaryKey', primaryKey, 'removedPkValue', removedPkValue_1);
948
+ }
949
+ else {
950
+ console.log('query', query);
951
+ }
952
+ try {
953
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
954
+ console.log(this.request);
955
+ 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');
956
+ 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');
957
+ console.trace();
958
+ console.groupEnd();
959
+ this.runLifecycleHooks("beforeExecution", {
960
+ config: this.config,
961
+ request: this.request
962
+ });
963
+ axiosActiveRequest = (_e = axios)[requestMethod.toLowerCase()].apply(_e, tslib.__spreadArray([restRequestUri], (function () {
964
+ var convert = function (data) {
965
+ return convertForRequestBody(data, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); });
966
+ };
967
+ var baseConfig = {
968
+ withCredentials: withCredentials,
969
+ };
970
+ switch (requestMethod) {
971
+ case GET:
972
+ return [tslib.__assign(tslib.__assign({}, baseConfig), { params: query })];
973
+ case POST:
974
+ if (dataInsertMultipleRows !== undefined) {
975
+ return [
976
+ dataInsertMultipleRows.map(convert),
977
+ baseConfig
978
+ ];
979
+ }
980
+ return [convert(query), baseConfig];
981
+ case PUT:
982
+ return [convert(query), baseConfig];
983
+ case DELETE:
984
+ return [tslib.__assign(tslib.__assign({}, baseConfig), { data: convert(query) })];
985
+ default:
986
+ throw new Error("The request method (".concat(requestMethod, ") was not recognized."));
987
+ }
988
+ })(), false));
989
+ if (cachingConfirmed) {
990
+ // push to cache so we do not repeat the request
991
+ exports.apiRequestCache.push({
992
+ requestArgumentsSerialized: querySerialized,
993
+ request: axiosActiveRequest
994
+ });
995
+ }
996
+ // todo - wip verify this works
997
+ // we had removed the value from the request to add to the URI.
998
+ addBackPK === null || addBackPK === void 0 ? void 0 : addBackPK(); // adding back so post-processing methods work
999
+ // returning the promise with this then is important for tests. todo - we could make that optional.
1000
+ // https://rapidapi.com/guides/axios-async-await
1001
+ return [2 /*return*/, axiosActiveRequest.then(function (response) { return tslib.__awaiter(_this, void 0, void 0, function () {
1002
+ var cacheIndex, callback, responseData_1, dependencies_1, fetchReferences_1, apiRequestPromises, _loop_1, _a, _b, _c, _i, tableToFetch;
1003
+ var _this = this;
1004
+ var _d, _e, _f, _g, _h, _j, _k;
1005
+ return tslib.__generator(this, function (_l) {
1006
+ switch (_l.label) {
1007
+ case 0:
1008
+ // noinspection SuspiciousTypeOfGuard
1009
+ if (typeof response.data === 'string') {
1010
+ if (isTest) {
1011
+ console.trace();
1012
+ 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 + ')');
1013
+ }
1014
+ return [2 /*return*/, Promise.reject(response)];
1015
+ }
1016
+ if (cachingConfirmed) {
1017
+ cacheIndex = exports.apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
1018
+ exports.apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction;
1019
+ // only cache get method requests
1020
+ exports.apiRequestCache[cacheIndex].response = response;
1021
+ }
1022
+ this.runLifecycleHooks("afterExecution", {
1023
+ config: this.config,
1024
+ request: this.request,
1025
+ response: response
1026
+ });
1027
+ // todo - this feels dumb now, but i digress
1028
+ apiResponse = TestRestfulResponse(response, success, error);
1029
+ if (false === apiResponse) {
1030
+ if (debug && isDevelopment) {
1031
+ reactToastify.toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
1032
+ }
1033
+ return [2 /*return*/, response];
1034
+ }
1035
+ callback = function () { return _this.runLifecycleHooks("afterCommit", {
1036
+ config: _this.config,
1037
+ request: _this.request,
1038
+ response: response
1039
+ }); };
1040
+ if (undefined !== reactBootstrap && response) {
1041
+ switch (requestMethod) {
1042
+ case GET:
1043
+ reactBootstrap.updateRestfulObjectArrays({
1044
+ dataOrCallback: Array.isArray(response.data.rest) ? response.data.rest : [response.data.rest],
1045
+ stateKey: this.config.restModel.TABLE_NAME,
1046
+ uniqueObjectId: this.config.restModel.PRIMARY_SHORT,
1047
+ callback: callback
1048
+ });
1049
+ break;
1050
+ case POST:
1051
+ this.postState(response, this.request, callback);
1052
+ break;
1053
+ case PUT:
1054
+ this.putState(response, this.request, callback);
1055
+ break;
1056
+ case DELETE:
1057
+ this.deleteState(response, this.request, callback);
1058
+ break;
1059
+ }
1060
+ }
1061
+ else {
1062
+ callback();
1063
+ }
1064
+ if (!(C6.GET === requestMethod)) return [3 /*break*/, 6];
1065
+ responseData_1 = response.data;
1066
+ returnGetNextPageFunction = 1 !== ((_d = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _d === void 0 ? void 0 : _d[C6.LIMIT]) &&
1067
+ ((_e = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _e === void 0 ? void 0 : _e[C6.LIMIT]) === responseData_1.rest.length;
1068
+ if (false === isTest || true === isVerbose) {
1069
+ 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');
1070
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
1071
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', this.request);
1072
+ console.log('%c Response Data:', 'color: #0c0', responseData_1.rest);
1073
+ 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);
1074
+ console.trace();
1075
+ console.groupEnd();
1076
+ }
1077
+ if (false === returnGetNextPageFunction
1078
+ && true === debug
1079
+ && isDevelopment) {
1080
+ 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);
1081
+ }
1082
+ if (!(fetchDependencies
1083
+ && 'number' === typeof fetchDependencies
1084
+ && responseData_1.rest.length > 0)) return [3 /*break*/, 6];
1085
+ console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
1086
+ + (fetchDependencies & exports.eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
1087
+ + (fetchDependencies & exports.eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
1088
+ + (fetchDependencies & exports.eFetchDependencies.C6ENTITY ? ' | (C6ENTITY)' : '')
1089
+ + (fetchDependencies & exports.eFetchDependencies.RECURSIVE ? ' | (RECURSIVE)' : ''), 'color: #33ccff');
1090
+ console.groupCollapsed('Collapsed JS Trace');
1091
+ console.trace(); // hidden in collapsed group
1092
+ console.groupEnd();
1093
+ dependencies_1 = {};
1094
+ if (fetchDependencies & exports.eFetchDependencies.C6ENTITY) {
1095
+ dependencies_1 = operatingTable.endsWith("carbon_carbons")
1096
+ ? tslib.__assign(tslib.__assign({}, fetchDependencies & exports.eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
1097
+ ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1098
+ : {}), fetchDependencies & exports.eFetchDependencies.PARENTS // REFERENCES === PARENTS
1099
+ ? C6.TABLES[operatingTable].TABLE_REFERENCES
1100
+ : {}) : tslib.__assign(tslib.__assign({}, fetchDependencies & exports.eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
1101
+ ? tslib.__assign(tslib.__assign({}, Object.keys(C6.TABLES[operatingTable].TABLE_REFERENCES).reduce(function (accumulator, columnName) {
1102
+ if (!C6.TABLES[operatingTable].PRIMARY_SHORT.includes(columnName)) {
1103
+ accumulator[columnName] = C6.TABLES[operatingTable].TABLE_REFERENCES[columnName];
1104
+ }
1105
+ return accumulator;
1106
+ }, {})), C6.TABLES[operatingTable].TABLE_REFERENCED_BY // it is unlikely that a C6 table will have any TABLE_REFERENCED_BY
1107
+ ) : {}), fetchDependencies & exports.eFetchDependencies.PARENTS // REFERENCES === PARENTS
1108
+ ? C6.TABLES[operatingTable].PRIMARY_SHORT.reduce(function (accumulator, primaryKey) {
1109
+ if (primaryKey in C6.TABLES[operatingTable].TABLE_REFERENCES) {
1110
+ accumulator[primaryKey] = C6.TABLES[operatingTable].TABLE_REFERENCES[primaryKey];
1111
+ }
1112
+ return accumulator;
1113
+ }, {})
1114
+ : {});
1115
+ }
1116
+ else {
1117
+ // this is the natural mysql context
1118
+ dependencies_1 = tslib.__assign(tslib.__assign({}, fetchDependencies & exports.eFetchDependencies.REFERENCED // REFERENCED === CHILDREN
1119
+ ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1120
+ : {}), fetchDependencies & exports.eFetchDependencies.REFERENCES // REFERENCES === PARENTS
1121
+ ? C6.TABLES[operatingTable].TABLE_REFERENCES
1122
+ : {});
1123
+ }
1124
+ fetchReferences_1 = {};
1125
+ apiRequestPromises = [];
1126
+ console.log('%c Dependencies', 'color: #005555', dependencies_1);
1127
+ Object.keys(dependencies_1)
1128
+ .forEach(function (column) { return dependencies_1[column]
1129
+ .forEach(function (constraint) {
1130
+ var _a, _b, _c, _d;
1131
+ var _e, _f, _g;
1132
+ var columnValues = (_b = (_a = responseData_1.rest[column]) !== null && _a !== void 0 ? _a : responseData_1.rest.map(function (row) {
1133
+ if (operatingTable.endsWith("carbons")
1134
+ && 'entity_tag' in row
1135
+ && !constraint.TABLE.endsWith(row['entity_tag'].split('\\').pop().toLowerCase())) {
1136
+ return false; // map
1137
+ }
1138
+ if (!(column in row)) {
1139
+ return false;
1140
+ }
1141
+ // todo - row[column] is a FK value, we should optionally remove values that are already in state
1142
+ // this could be any column in the table constraint.TABLE, not just the primary key
1143
+ return row[column];
1144
+ }).filter(function (n) { return n; })) !== null && _b !== void 0 ? _b : [];
1145
+ if (columnValues.length === 0) {
1146
+ return; // forEach
1147
+ }
1148
+ (_c = fetchReferences_1[_e = constraint.TABLE]) !== null && _c !== void 0 ? _c : (fetchReferences_1[_e] = {});
1149
+ (_d = (_f = fetchReferences_1[constraint.TABLE])[_g = constraint.COLUMN]) !== null && _d !== void 0 ? _d : (_f[_g] = []);
1150
+ fetchReferences_1[constraint.TABLE][constraint.COLUMN].push(columnValues);
1151
+ }); });
1152
+ console.log('fetchReferences', fetchReferences_1);
1153
+ _loop_1 = function (tableToFetch) {
1154
+ var referencesTables, shouldContinue, fetchTable, RestApi, nextFetchDependencies;
1155
+ var _m;
1156
+ return tslib.__generator(this, function (_o) {
1157
+ switch (_o.label) {
1158
+ case 0:
1159
+ if (fetchDependencies & exports.eFetchDependencies.C6ENTITY
1160
+ && 'string' === typeof tableName
1161
+ && tableName.endsWith("carbon_carbons")) {
1162
+ referencesTables = responseData_1.rest.reduce(function (accumulator, row) {
1163
+ if ('entity_tag' in row && !accumulator.includes(row['entity_tag'])) {
1164
+ accumulator.push(row['entity_tag']);
1165
+ }
1166
+ return accumulator;
1167
+ }, []).map(function (entityTag) { return entityTag.split('\\').pop().toLowerCase(); });
1168
+ shouldContinue = referencesTables.find(function (referencesTable) { return tableToFetch.endsWith(referencesTable); });
1169
+ if (!shouldContinue) {
1170
+ console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables);
1171
+ return [2 /*return*/, "continue"];
1172
+ }
1173
+ console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') will be fetched.', 'color: #0c0');
1174
+ }
1175
+ return [4 /*yield*/, C6.IMPORT(tableToFetch)];
1176
+ case 1:
1177
+ fetchTable = _o.sent();
1178
+ RestApi = fetchTable.default;
1179
+ console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff');
1180
+ nextFetchDependencies = exports.eFetchDependencies.NONE;
1181
+ if (fetchDependencies & exports.eFetchDependencies.RECURSIVE) {
1182
+ if (fetchDependencies & exports.eFetchDependencies.ALL) {
1183
+ 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.');
1184
+ }
1185
+ nextFetchDependencies = fetchDependencies;
1186
+ }
1187
+ else if (fetchDependencies & exports.eFetchDependencies.C6ENTITY) {
1188
+ if (tableToFetch === "carbon_carbons") {
1189
+ nextFetchDependencies = fetchDependencies;
1190
+ }
1191
+ else {
1192
+ nextFetchDependencies = fetchDependencies ^ exports.eFetchDependencies.C6ENTITY;
1193
+ }
1194
+ }
1195
+ console.log('fetchReferences', fetchReferences_1[tableToFetch], "Current fetchDependencies for (" + operatingTable + "):", fetchDependencies, "New fetchDependencies for (" + tableToFetch + "): ", nextFetchDependencies);
1196
+ // 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
1197
+ // it not certain that they are using carbons' entities either
1198
+ // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
1199
+ // todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
1200
+ apiRequestPromises.push(RestApi.Get((_m = {},
1201
+ _m[C6.WHERE] = {
1202
+ 0: Object.keys(fetchReferences_1[tableToFetch]).reduce(function (sum, column) {
1203
+ fetchReferences_1[tableToFetch][column] = fetchReferences_1[tableToFetch][column].flat(Infinity);
1204
+ if (0 === fetchReferences_1[tableToFetch][column].length) {
1205
+ console.warn('The column (' + column + ') was not found in the response data. We will not fetch.', responseData_1);
1206
+ return false;
1207
+ }
1208
+ sum[column] = fetchReferences_1[tableToFetch][column].length === 1
1209
+ ? fetchReferences_1[tableToFetch][column][0]
1210
+ : [
1211
+ C6.IN, fetchReferences_1[tableToFetch][column]
1212
+ ];
1213
+ return sum;
1214
+ }, {})
1215
+ },
1216
+ _m.fetchDependencies = nextFetchDependencies,
1217
+ _m)));
1218
+ return [2 /*return*/];
1219
+ }
1220
+ });
1221
+ };
1222
+ _a = fetchReferences_1;
1223
+ _b = [];
1224
+ for (_c in _a)
1225
+ _b.push(_c);
1226
+ _i = 0;
1227
+ _l.label = 1;
1228
+ case 1:
1229
+ if (!(_i < _b.length)) return [3 /*break*/, 4];
1230
+ _c = _b[_i];
1231
+ if (!(_c in _a)) return [3 /*break*/, 3];
1232
+ tableToFetch = _c;
1233
+ return [5 /*yield**/, _loop_1(tableToFetch)];
1234
+ case 2:
1235
+ _l.sent();
1236
+ _l.label = 3;
1237
+ case 3:
1238
+ _i++;
1239
+ return [3 /*break*/, 1];
1240
+ case 4:
1241
+ console.groupEnd();
1242
+ return [4 /*yield*/, Promise.all(apiRequestPromises)];
1243
+ case 5:
1244
+ _l.sent();
1245
+ apiRequestPromises.map(function (promise) { return tslib.__awaiter(_this, void 0, void 0, function () {
1246
+ var _a, _b;
1247
+ return tslib.__generator(this, function (_c) {
1248
+ switch (_c.label) {
1249
+ case 0:
1250
+ if (!Array.isArray(this.request.fetchDependencies)) {
1251
+ // to reassign value we must ref the root
1252
+ this.request.fetchDependencies = [];
1253
+ }
1254
+ _b = (_a = this.request.fetchDependencies).push;
1255
+ return [4 /*yield*/, promise];
1256
+ case 1:
1257
+ _b.apply(_a, [_c.sent()]);
1258
+ return [2 /*return*/];
1259
+ }
1260
+ });
1261
+ }); });
1262
+ _l.label = 6;
1263
+ case 6:
1264
+ if (debug && isDevelopment) {
1265
+ reactToastify.toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1266
+ }
1267
+ return [2 /*return*/, response];
1268
+ }
1269
+ });
1270
+ }); })];
1271
+ }
1272
+ catch (throwableError) {
1273
+ if (isTest) {
1274
+ throw new Error(JSON.stringify(throwableError));
1275
+ }
1276
+ console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
1277
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
1278
+ console.warn(throwableError);
1279
+ console.trace();
1280
+ console.groupEnd();
1281
+ TestRestfulResponse(throwableError, success, error);
1282
+ return [2 /*return*/, null];
1283
+ }
1284
+ return [2 /*return*/];
1285
+ });
1286
+ }); };
1287
+ return [4 /*yield*/, apiRequest()];
835
1288
  case 2: return [2 /*return*/, _b.sent()];
836
1289
  }
837
1290
  });
@@ -1125,7 +1578,6 @@ exports.group = group;
1125
1578
  exports.info = info;
1126
1579
  exports.isLocal = isDevelopment;
1127
1580
  exports.isNode = isNode;
1128
- exports.isPromise = isPromise;
1129
1581
  exports.isTest = isTest;
1130
1582
  exports.isVerbose = isVerbose;
1131
1583
  exports.onError = onError;