@carbonorm/carbonnode 2.0.34 → 3.0.0

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.
Files changed (77) hide show
  1. package/dist/api/carbonSqlExecutor.d.ts +17 -0
  2. package/dist/api/interfaces/ormInterfaces.d.ts +22 -1
  3. package/dist/api/rest/Blog_Categories.d.ts +37 -0
  4. package/dist/api/rest/Blog_Categories.test.d.ts +11 -0
  5. package/dist/api/rest/Blog_Images.d.ts +37 -0
  6. package/dist/api/rest/Blog_Images.test.d.ts +15 -0
  7. package/dist/api/rest/Blog_Post_Categories.d.ts +37 -0
  8. package/dist/api/rest/Blog_Post_Categories.test.d.ts +13 -0
  9. package/dist/api/rest/Blog_Post_Tags.d.ts +37 -0
  10. package/dist/api/rest/Blog_Post_Tags.test.d.ts +13 -0
  11. package/dist/api/rest/Blog_Posts.d.ts +37 -0
  12. package/dist/api/rest/Blog_Posts.test.d.ts +21 -0
  13. package/dist/api/rest/Blog_Tags.d.ts +37 -0
  14. package/dist/api/rest/Blog_Tags.test.d.ts +11 -0
  15. package/dist/api/rest/C6.d.ts +1000 -0
  16. package/dist/api/rest/Cache.d.ts +37 -0
  17. package/dist/api/rest/Cache.test.d.ts +12 -0
  18. package/dist/api/rest/Cities.d.ts +37 -0
  19. package/dist/api/rest/Cities.test.d.ts +17 -0
  20. package/dist/api/rest/Counties.d.ts +37 -0
  21. package/dist/api/rest/Counties.test.d.ts +18 -0
  22. package/dist/api/rest/Countries.d.ts +37 -0
  23. package/dist/api/rest/Countries.test.d.ts +24 -0
  24. package/dist/api/rest/Geometries.d.ts +37 -0
  25. package/dist/api/rest/Geometries.test.d.ts +16 -0
  26. package/dist/api/rest/Images.d.ts +37 -0
  27. package/dist/api/rest/Images.test.d.ts +16 -0
  28. package/dist/api/rest/Land_Section_Info.d.ts +37 -0
  29. package/dist/api/rest/Land_Section_Info.test.d.ts +15 -0
  30. package/dist/api/rest/Neighborhoods.d.ts +37 -0
  31. package/dist/api/rest/Neighborhoods.test.d.ts +12 -0
  32. package/dist/api/rest/Parcel_Building_Details.d.ts +37 -0
  33. package/dist/api/rest/Parcel_Building_Details.test.d.ts +40 -0
  34. package/dist/api/rest/Parcel_Neighborhoods.d.ts +37 -0
  35. package/dist/api/rest/Parcel_Neighborhoods.test.d.ts +15 -0
  36. package/dist/api/rest/Parcel_Owners.d.ts +37 -0
  37. package/dist/api/rest/Parcel_Owners.test.d.ts +23 -0
  38. package/dist/api/rest/Parcel_Sales.d.ts +37 -0
  39. package/dist/api/rest/Parcel_Sales.test.d.ts +19 -0
  40. package/dist/api/rest/Parcel_Tax_History.d.ts +37 -0
  41. package/dist/api/rest/Parcel_Tax_History.test.d.ts +24 -0
  42. package/dist/api/rest/Parcels.d.ts +37 -0
  43. package/dist/api/rest/Parcels.test.d.ts +42 -0
  44. package/dist/api/rest/Payment_Charge_Logs.d.ts +37 -0
  45. package/dist/api/rest/Payment_Charge_Logs.test.d.ts +17 -0
  46. package/dist/api/rest/Payment_Subscriptions.d.ts +37 -0
  47. package/dist/api/rest/Payment_Subscriptions.test.d.ts +20 -0
  48. package/dist/api/rest/Property_Units.d.ts +37 -0
  49. package/dist/api/rest/Property_Units.test.d.ts +55 -0
  50. package/dist/api/rest/Sources.d.ts +37 -0
  51. package/dist/api/rest/Sources.test.d.ts +17 -0
  52. package/dist/api/rest/States.d.ts +37 -0
  53. package/dist/api/rest/States.test.d.ts +20 -0
  54. package/dist/api/rest/Tax_Districts.d.ts +37 -0
  55. package/dist/api/rest/Tax_Districts.test.d.ts +12 -0
  56. package/dist/api/rest/Users.d.ts +37 -0
  57. package/dist/api/rest/Users.test.d.ts +14 -0
  58. package/dist/api/rest/Valuation_Reports.d.ts +37 -0
  59. package/dist/api/rest/Valuation_Reports.test.d.ts +36 -0
  60. package/dist/api/rest/Zip_Codes.d.ts +37 -0
  61. package/dist/api/rest/Zip_Codes.test.d.ts +15 -0
  62. package/dist/api/restRequest.d.ts +39 -16
  63. package/dist/index.cjs.js +881 -454
  64. package/dist/index.cjs.js.map +1 -1
  65. package/dist/index.d.ts +3 -0
  66. package/dist/index.esm.js +881 -456
  67. package/dist/index.esm.js.map +1 -1
  68. package/dist/variables/isNode.d.ts +2 -0
  69. package/package.json +14 -4
  70. package/scripts/assets/handlebars/C6.ts.handlebars +5 -1
  71. package/scripts/generateRestBindings.cjs +89 -23
  72. package/scripts/generateRestBindings.ts +100 -27
  73. package/src/api/carbonSqlExecutor.ts +279 -0
  74. package/src/api/interfaces/ormInterfaces.ts +9 -1
  75. package/src/api/restRequest.ts +164 -19
  76. package/src/index.ts +3 -0
  77. package/src/variables/isNode.ts +3 -0
package/dist/index.cjs.js CHANGED
@@ -235,6 +235,366 @@ var axiosInstance = (axios.create({
235
235
  */
236
236
  }));
237
237
 
238
+ // import { validatePayloadAgainstSchema } from './validator'; // C6 schema validator
239
+ var CarbonSqlExecutor = /** @class */ (function () {
240
+ function CarbonSqlExecutor(pool, C6) {
241
+ this.pool = pool;
242
+ this.C6 = C6;
243
+ }
244
+ CarbonSqlExecutor.prototype.withConnection = function (cb) {
245
+ return tslib.__awaiter(this, void 0, void 0, function () {
246
+ var conn;
247
+ return tslib.__generator(this, function (_a) {
248
+ switch (_a.label) {
249
+ case 0: return [4 /*yield*/, this.pool.getConnection()];
250
+ case 1:
251
+ conn = _a.sent();
252
+ _a.label = 2;
253
+ case 2:
254
+ _a.trys.push([2, , 4, 5]);
255
+ return [4 /*yield*/, cb(conn)];
256
+ case 3: return [2 /*return*/, _a.sent()];
257
+ case 4:
258
+ conn.release();
259
+ return [7 /*endfinally*/];
260
+ case 5: return [2 /*return*/];
261
+ }
262
+ });
263
+ });
264
+ };
265
+ CarbonSqlExecutor.prototype.handle = function (req, res, next) {
266
+ return tslib.__awaiter(this, void 0, void 0, function () {
267
+ var method, table, primary, payload, result, _a, err_1;
268
+ return tslib.__generator(this, function (_b) {
269
+ switch (_b.label) {
270
+ case 0:
271
+ _b.trys.push([0, 11, , 12]);
272
+ method = req.method.toUpperCase();
273
+ table = req.params.table;
274
+ primary = req.params.primary;
275
+ payload = method === 'GET' ? req.query : req.body;
276
+ if (!(table in this.C6.TABLES)) {
277
+ res.status(400).json({ error: "Invalid table: ".concat(table) });
278
+ return [2 /*return*/];
279
+ }
280
+ result = void 0;
281
+ _a = method;
282
+ switch (_a) {
283
+ case 'GET': return [3 /*break*/, 1];
284
+ case 'OPTIONS': return [3 /*break*/, 1];
285
+ case 'POST': return [3 /*break*/, 3];
286
+ case 'PUT': return [3 /*break*/, 5];
287
+ case 'DELETE': return [3 /*break*/, 7];
288
+ }
289
+ return [3 /*break*/, 9];
290
+ case 1: return [4 /*yield*/, this.select(table, primary, payload)];
291
+ case 2:
292
+ result = _b.sent();
293
+ return [3 /*break*/, 10];
294
+ case 3: return [4 /*yield*/, this.insert(table, payload)];
295
+ case 4:
296
+ result = _b.sent();
297
+ return [3 /*break*/, 10];
298
+ case 5: return [4 /*yield*/, this.update(table, primary, payload)];
299
+ case 6:
300
+ result = _b.sent();
301
+ return [3 /*break*/, 10];
302
+ case 7: return [4 /*yield*/, this.delete(table, primary, payload)];
303
+ case 8:
304
+ result = _b.sent();
305
+ return [3 /*break*/, 10];
306
+ case 9: throw new Error("Unsupported method: ".concat(method));
307
+ case 10:
308
+ res.status(200).json({ success: true, result: result });
309
+ return [3 /*break*/, 12];
310
+ case 11:
311
+ err_1 = _b.sent();
312
+ next(err_1);
313
+ return [3 /*break*/, 12];
314
+ case 12: return [2 /*return*/];
315
+ }
316
+ });
317
+ });
318
+ };
319
+ CarbonSqlExecutor.prototype.buildBooleanJoinedConditions = function (set, andMode) {
320
+ if (andMode === void 0) { andMode = true; }
321
+ var booleanOperator = andMode ? 'AND' : 'OR';
322
+ var sql = '';
323
+ var OPERATORS = ['=', '!=', '<', '<=', '>', '>=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'IS', 'IS NOT'];
324
+ var isAggregateArray = function (value) { return Array.isArray(value) && typeof value[0] === 'string' && OPERATORS.includes(value[0]); };
325
+ var isNumericKeyed = function (obj) { return Array.isArray(obj) && Object.keys(obj).every(function (k) { return /^\d+$/.test(k); }); };
326
+ // todo - we should be doing something with value no????
327
+ var addCondition = function (column, op, _value) {
328
+ var paramName = column.replace(/\W+/g, '_');
329
+ return "(".concat(column, " ").concat(op, " :").concat(paramName, ")");
330
+ };
331
+ if (isNumericKeyed(set)) {
332
+ switch (set.length) {
333
+ case 2:
334
+ sql += addCondition(set[0], '=', set[1]);
335
+ break;
336
+ case 3:
337
+ if (!OPERATORS.includes(set[1])) {
338
+ throw new Error("Invalid operator: ".concat(set[1]));
339
+ }
340
+ sql += addCondition(set[0], set[1], set[2]);
341
+ break;
342
+ default:
343
+ throw new Error("Invalid array condition: ".concat(JSON.stringify(set)));
344
+ }
345
+ }
346
+ else {
347
+ var parts = [];
348
+ for (var _i = 0, _a = Object.entries(set); _i < _a.length; _i++) {
349
+ var _b = _a[_i], key = _b[0], value = _b[1];
350
+ if (/^\d+$/.test(key)) {
351
+ parts.push(this.buildBooleanJoinedConditions(value, !andMode));
352
+ continue;
353
+ }
354
+ if (!Array.isArray(value) || isAggregateArray(value)) {
355
+ parts.push(addCondition(key, '='));
356
+ continue;
357
+ }
358
+ if (value.length === 2 && OPERATORS.includes(value[0])) {
359
+ parts.push(addCondition(key, value[0], value[1]));
360
+ }
361
+ else if (value.length === 1 && isAggregateArray(value[0])) {
362
+ parts.push(addCondition(key, '=', value[0]));
363
+ }
364
+ else {
365
+ throw new Error("Invalid condition for ".concat(key, ": ").concat(JSON.stringify(value)));
366
+ }
367
+ }
368
+ sql = parts.join(" ".concat(booleanOperator, " "));
369
+ }
370
+ return "(".concat(sql, ")");
371
+ };
372
+ CarbonSqlExecutor.prototype.buildAggregateField = function (field) {
373
+ if (typeof field === 'string')
374
+ return field;
375
+ if (!Array.isArray(field))
376
+ throw new Error('Invalid SELECT entry: must be string or array');
377
+ var agg = field[0], args = field.slice(1);
378
+ switch (agg) {
379
+ case 'COUNT':
380
+ return "COUNT(".concat(args[0] || '*', ")");
381
+ case 'SUM':
382
+ case 'AVG':
383
+ case 'MIN':
384
+ case 'MAX':
385
+ return "".concat(agg, "(").concat(args[0], ")").concat(args[1] ? " AS ".concat(args[1]) : '');
386
+ case 'DISTINCT':
387
+ return "DISTINCT(".concat(args[0], ")").concat(args[1] ? " AS ".concat(args[1]) : '');
388
+ case 'GROUP_CONCAT': {
389
+ var col = args[0], alias = args[1], sortCol = args[2], sortType = args[3];
390
+ var order = sortCol ? " ORDER BY ".concat(sortCol, " ").concat(sortType || 'ASC') : '';
391
+ return "GROUP_CONCAT(DISTINCT ".concat(col).concat(order, " SEPARATOR ',')").concat(alias ? " AS ".concat(alias) : '');
392
+ }
393
+ case 'AS': {
394
+ var col = args[0], alias = args[1];
395
+ return "".concat(col, " AS ").concat(alias);
396
+ }
397
+ case 'CONVERT_TZ': {
398
+ var ts = args[0], fromTz = args[1], toTz = args[2];
399
+ return "CONVERT_TZ(".concat(ts, ", ").concat(fromTz, ", ").concat(toTz, ")");
400
+ }
401
+ case 'NOW':
402
+ return 'NOW()';
403
+ default:
404
+ throw new Error("Unsupported aggregate: ".concat(agg));
405
+ }
406
+ };
407
+ CarbonSqlExecutor.prototype.buildSelectQuery = function (table, primary, args, isSubSelect) {
408
+ var _this = this;
409
+ var _a, _b, _c, _d;
410
+ if (isSubSelect === void 0) { isSubSelect = false; }
411
+ var selectList = (_a = args === null || args === void 0 ? void 0 : args[this.C6.SELECT]) !== null && _a !== void 0 ? _a : ['*'];
412
+ var selectFields = Array.isArray(selectList)
413
+ ? selectList.map(function (f) { return _this.buildAggregateField(f); }).join(', ')
414
+ : '*';
415
+ var sql = "SELECT ".concat(selectFields, " FROM `").concat(table, "`");
416
+ if (args === null || args === void 0 ? void 0 : args[this.C6.JOIN]) {
417
+ var joins = args[this.C6.JOIN];
418
+ for (var joinType in joins) {
419
+ var joinKeyword = joinType.replace('_', ' ').toUpperCase();
420
+ for (var joinTable in joins[joinType]) {
421
+ var onClause = this.buildBooleanJoinedConditions(joins[joinType][joinTable]);
422
+ sql += " ".concat(joinKeyword, " JOIN `").concat(joinTable, "` ON ").concat(onClause);
423
+ }
424
+ }
425
+ }
426
+ if (args === null || args === void 0 ? void 0 : args[this.C6.WHERE]) {
427
+ sql += " WHERE ".concat(this.buildBooleanJoinedConditions(args[this.C6.WHERE]));
428
+ }
429
+ if (args === null || args === void 0 ? void 0 : args[this.C6.GROUP_BY]) {
430
+ var groupByFields = Array.isArray(args[this.C6.GROUP_BY]) ? args[this.C6.GROUP_BY].join(', ') : args[this.C6.GROUP_BY];
431
+ sql += " GROUP BY ".concat(groupByFields);
432
+ }
433
+ if (args === null || args === void 0 ? void 0 : args[this.C6.HAVING]) {
434
+ sql += " HAVING ".concat(this.buildBooleanJoinedConditions(args[this.C6.HAVING]));
435
+ }
436
+ if (args === null || args === void 0 ? void 0 : args[this.C6.PAGINATION]) {
437
+ var p = args[this.C6.PAGINATION];
438
+ var limitClause = '';
439
+ if (p[this.C6.ORDER]) {
440
+ var orderArray = Object.entries(p[this.C6.ORDER]).map(function (_a) {
441
+ var col = _a[0], dir = _a[1];
442
+ if (!['ASC', 'DESC'].includes(String(dir).toUpperCase())) {
443
+ throw new Error("Invalid order direction: ".concat(dir));
444
+ }
445
+ return "".concat(col, " ").concat(String(dir).toUpperCase());
446
+ });
447
+ sql += " ORDER BY ".concat(orderArray.join(', '));
448
+ }
449
+ else if (primary) {
450
+ sql += " ORDER BY ".concat(primary, " DESC");
451
+ }
452
+ else {
453
+ // todo this is wrong
454
+ var primaryKey = (_c = (_b = this.C6.TABLES['users'].PRIMARY_SHORT) === null || _b === void 0 ? void 0 : _b[0]) !== null && _c !== void 0 ? _c : 'user_id';
455
+ sql += " ORDER BY ".concat(primaryKey, " DESC");
456
+ }
457
+ if (p[this.C6.LIMIT] != null) {
458
+ var limit = parseInt(p[this.C6.LIMIT], 10);
459
+ if (isNaN(limit) || limit < 0) {
460
+ throw new Error("Invalid LIMIT: ".concat(p[this.C6.LIMIT]));
461
+ }
462
+ var page = parseInt((_d = p[this.C6.PAGE]) !== null && _d !== void 0 ? _d : 1, 10);
463
+ if (isNaN(page) || page < 1) {
464
+ throw new Error("PAGE must be >= 1 (got ".concat(p[this.C6.PAGE], ")"));
465
+ }
466
+ var offset = (page - 1) * limit;
467
+ limitClause += " LIMIT ".concat(offset, ", ").concat(limit);
468
+ }
469
+ sql += limitClause;
470
+ }
471
+ else if (!isSubSelect && primary) {
472
+ sql += " ORDER BY ".concat(primary, " ASC LIMIT 1");
473
+ }
474
+ else if (!isSubSelect && !primary) {
475
+ sql += " ORDER BY id ASC LIMIT 100"; // fallback default limit
476
+ }
477
+ return sql;
478
+ };
479
+ CarbonSqlExecutor.prototype.select = function (table, primary, args) {
480
+ return tslib.__awaiter(this, void 0, void 0, function () {
481
+ var sql;
482
+ var _this = this;
483
+ return tslib.__generator(this, function (_a) {
484
+ switch (_a.label) {
485
+ case 0:
486
+ sql = this.buildSelectQuery(table, primary, args);
487
+ return [4 /*yield*/, this.withConnection(function (conn) { return tslib.__awaiter(_this, void 0, void 0, function () {
488
+ var rows;
489
+ return tslib.__generator(this, function (_a) {
490
+ switch (_a.label) {
491
+ case 0:
492
+ console.log(sql);
493
+ return [4 /*yield*/, conn.query(sql)];
494
+ case 1:
495
+ rows = (_a.sent())[0];
496
+ return [2 /*return*/, rows];
497
+ }
498
+ });
499
+ }); })];
500
+ case 1: return [2 /*return*/, _a.sent()];
501
+ }
502
+ });
503
+ });
504
+ };
505
+ CarbonSqlExecutor.prototype.insert = function (table, data) {
506
+ return tslib.__awaiter(this, void 0, void 0, function () {
507
+ var keys, values, placeholders, sql;
508
+ var _this = this;
509
+ return tslib.__generator(this, function (_a) {
510
+ switch (_a.label) {
511
+ case 0:
512
+ keys = Object.keys(data);
513
+ values = keys.map(function (k) { return data[k]; });
514
+ placeholders = keys.map(function () { return '?'; }).join(', ');
515
+ sql = "INSERT INTO `".concat(table, "` (").concat(keys.join(', '), ") VALUES (").concat(placeholders, ")");
516
+ return [4 /*yield*/, this.withConnection(function (conn) { return tslib.__awaiter(_this, void 0, void 0, function () {
517
+ var result;
518
+ return tslib.__generator(this, function (_a) {
519
+ switch (_a.label) {
520
+ case 0: return [4 /*yield*/, conn.execute(sql, values)];
521
+ case 1:
522
+ result = (_a.sent())[0];
523
+ return [2 /*return*/, result];
524
+ }
525
+ });
526
+ }); })];
527
+ case 1: return [2 /*return*/, _a.sent()];
528
+ }
529
+ });
530
+ });
531
+ };
532
+ CarbonSqlExecutor.prototype.update = function (table, primary, data) {
533
+ return tslib.__awaiter(this, void 0, void 0, function () {
534
+ var keys, values, updates, sql;
535
+ var _this = this;
536
+ return tslib.__generator(this, function (_a) {
537
+ switch (_a.label) {
538
+ case 0:
539
+ if (!primary) {
540
+ throw new Error('Primary key is required for update');
541
+ }
542
+ keys = Object.keys(data);
543
+ values = keys.map(function (k) { return data[k]; });
544
+ updates = keys.map(function (k) { return "`".concat(k, "` = ?"); }).join(', ');
545
+ sql = "UPDATE `".concat(table, "` SET ").concat(updates, " WHERE `").concat(primary, "` = ?");
546
+ values.push(data[primary]);
547
+ return [4 /*yield*/, this.withConnection(function (conn) { return tslib.__awaiter(_this, void 0, void 0, function () {
548
+ var result;
549
+ return tslib.__generator(this, function (_a) {
550
+ switch (_a.label) {
551
+ case 0: return [4 /*yield*/, conn.execute(sql, values)];
552
+ case 1:
553
+ result = (_a.sent())[0];
554
+ return [2 /*return*/, result];
555
+ }
556
+ });
557
+ }); })];
558
+ case 1: return [2 /*return*/, _a.sent()];
559
+ }
560
+ });
561
+ });
562
+ };
563
+ CarbonSqlExecutor.prototype.delete = function (table, primary, args) {
564
+ return tslib.__awaiter(this, void 0, void 0, function () {
565
+ var sql;
566
+ var _this = this;
567
+ return tslib.__generator(this, function (_a) {
568
+ switch (_a.label) {
569
+ case 0:
570
+ if (!primary || !(args === null || args === void 0 ? void 0 : args[primary])) {
571
+ throw new Error('Primary key and value required for delete');
572
+ }
573
+ sql = "DELETE FROM `".concat(table, "` WHERE `").concat(primary, "` = ?");
574
+ return [4 /*yield*/, this.withConnection(function (conn) { return tslib.__awaiter(_this, void 0, void 0, function () {
575
+ var result;
576
+ return tslib.__generator(this, function (_a) {
577
+ switch (_a.label) {
578
+ case 0: return [4 /*yield*/, conn.execute(sql, [args[primary]])];
579
+ case 1:
580
+ result = (_a.sent())[0];
581
+ return [2 /*return*/, result];
582
+ }
583
+ });
584
+ }); })];
585
+ case 1: return [2 /*return*/, _a.sent()];
586
+ }
587
+ });
588
+ });
589
+ };
590
+ return CarbonSqlExecutor;
591
+ }());
592
+
593
+ var carbonSqlExecutor = /*#__PURE__*/Object.freeze({
594
+ __proto__: null,
595
+ CarbonSqlExecutor: CarbonSqlExecutor
596
+ });
597
+
238
598
  function convertForRequestBody (restfulObject, tableName, C6, regexErrorHandler) {
239
599
  if (regexErrorHandler === void 0) { regexErrorHandler = alert; }
240
600
  var payload = {};
@@ -306,6 +666,9 @@ function convertForRequestBody (restfulObject, tableName, C6, regexErrorHandler)
306
666
  }, {});
307
667
  }
308
668
 
669
+ var _a;
670
+ var isNode = typeof process !== 'undefined' && !!((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node);
671
+
309
672
  function getEnvVar(key, fallback) {
310
673
  if (fallback === void 0) { fallback = ''; }
311
674
  // Vite-style injection
@@ -476,7 +839,8 @@ function extendedTypeHints() {
476
839
  return function (argv) { return restRequest(argv); };
477
840
  }
478
841
  function restRequest(_a) {
479
- var C6 = _a.C6, _b = _a.axios, axios = _b === void 0 ? axiosInstance : _b, _c = _a.restURL, restURL = _c === void 0 ? '/rest/' : _c, _d = _a.withCredentials, withCredentials = _d === void 0 ? true : _d, tableName = _a.tableName, _e = _a.requestMethod, requestMethod = _e === void 0 ? GET : _e, _f = _a.queryCallback, queryCallback = _f === void 0 ? {} : _f, responseCallback = _a.responseCallback, _g = _a.skipPrimaryCheck, skipPrimaryCheck = _g === void 0 ? false : _g, _h = _a.clearCache, clearCache = _h === void 0 ? undefined : _h;
842
+ var _this = this;
843
+ var C6 = _a.C6, _b = _a.axios, axios = _b === void 0 ? axiosInstance : _b, _c = _a.restURL, restURL = _c === void 0 ? '/rest/' : _c, mysqlPool = _a.mysqlPool, _d = _a.withCredentials, withCredentials = _d === void 0 ? true : _d, tableName = _a.tableName, _e = _a.requestMethod, requestMethod = _e === void 0 ? GET : _e, _f = _a.queryCallback, queryCallback = _f === void 0 ? {} : _f, responseCallback = _a.responseCallback, _g = _a.skipPrimaryCheck, skipPrimaryCheck = _g === void 0 ? false : _g, _h = _a.clearCache, clearCache = _h === void 0 ? undefined : _h;
480
844
  var fullTableList = Array.isArray(tableName) ? tableName : [tableName];
481
845
  var operatingTableFullName = fullTableList[0];
482
846
  var operatingTable = removePrefixIfExists(operatingTableFullName, C6.PREFIX);
@@ -493,483 +857,544 @@ function restRequest(_a) {
493
857
  if (null !== clearCache || undefined !== clearCache) {
494
858
  userCustomClearCache[tables + requestMethod] = clearCache;
495
859
  }
496
- return function (request) {
497
- if (request === void 0) { request = {}; }
498
- console.groupCollapsed('%c API: (' + requestMethod + ') Request for (' + operatingTable + ')', 'color: #0c0');
499
- console.log('request', request);
500
- console.groupEnd();
501
- // an undefined query would indicate queryCallback returned undefined,
502
- // thus the request shouldn't fire as is in custom cache
503
- var query;
504
- if ('function' === typeof queryCallback) {
505
- query = queryCallback(request); // obj or obj[]
506
- }
507
- else {
508
- query = queryCallback;
509
- }
510
- if (undefined === query || null === query) {
511
- if (request.debug && isDevelopment) {
512
- reactToastify.toast.warning("DEV: queryCallback returned undefined, signaling in Custom Cache. (returning null)", toastOptionsDevs);
513
- }
514
- console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') undefined, returning null (will not fire ajax)!', 'color: #c00');
515
- 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');
516
- console.trace();
517
- console.groupEnd();
518
- return null;
519
- }
520
- if (C6.GET === requestMethod) {
521
- if (undefined === query[C6.PAGINATION]) {
522
- query[C6.PAGINATION] = {};
523
- }
524
- query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
525
- query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
860
+ return function () {
861
+ var args_1 = [];
862
+ for (var _i = 0; _i < arguments.length; _i++) {
863
+ args_1[_i] = arguments[_i];
526
864
  }
527
- // this could return itself with a new page number, or undefined if the end is reached
528
- function apiRequest() {
529
- var _this = this;
530
- var _a, _b, _c, _d, _e, _f, _g;
531
- (_a = request.cacheResults) !== null && _a !== void 0 ? _a : (request.cacheResults = C6.GET === requestMethod);
532
- if (C6.GET === requestMethod
533
- && undefined !== ((_b = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _b === void 0 ? void 0 : _b[C6.PAGE])
534
- && 1 !== query[C6.PAGINATION][C6.PAGE]) {
535
- console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
536
- console.log('Request Data (note you may see the success and/or error prompt):', request);
537
- console.trace();
538
- console.groupEnd();
539
- }
540
- // The problem with creating cache keys with a stringified object is the order of keys matters and it's possible for the same query to be stringified differently.
541
- // Here we ensure the key order will be identical between two of the same requests. https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key
542
- // literally impossible for query to be undefined or null here but the editor is too busy licking windows to understand that
543
- var querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
544
- var cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
545
- var cachingConfirmed = false;
546
- // determine if we need to paginate.
547
- if (requestMethod === C6.GET) {
548
- if (undefined === (query === null || query === void 0 ? void 0 : query[C6.PAGINATION])) {
549
- if (undefined === query || null === query) {
550
- query = {};
551
- }
552
- query[C6.PAGINATION] = {};
553
- }
554
- query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
555
- query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
556
- // this will evaluate true most the time
557
- if (true === request.cacheResults) {
558
- // just find the next, non-fetched, page and return a function to request it
559
- if (undefined !== cacheResult) {
560
- do {
561
- var cacheCheck = checkCache(cacheResult, requestMethod, tableName, request);
562
- if (false !== cacheCheck) {
563
- return cacheCheck;
564
- }
565
- // this line incrementing page is why we return recursively
566
- ++query[C6.PAGINATION][C6.PAGE];
567
- // this json stringify is to capture the new page number
568
- querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
569
- cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
570
- } while (undefined !== cacheResult);
571
- if (request.debug && isDevelopment) {
572
- reactToastify.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);
573
- }
574
- // @ts-ignore - this is an incorrect warning on TS, it's well typed
575
- return apiRequest;
576
- }
577
- cachingConfirmed = true;
578
- }
579
- else {
580
- if (request.debug && isDevelopment) {
581
- reactToastify.toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
582
- }
583
- }
584
- if (request.debug && isDevelopment) {
585
- reactToastify.toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
586
- }
587
- }
588
- else if (request.cacheResults) { // if we are not getting, we are updating, deleting, or inserting
589
- if (cacheResult) {
590
- var cacheCheck = checkCache(cacheResult, requestMethod, tableName, request);
591
- if (false !== cacheCheck) {
592
- return cacheCheck;
593
- }
594
- }
595
- cachingConfirmed = true;
596
- // push to cache so we do not repeat the request
597
- }
598
- var addBackPK;
599
- var apiResponse;
600
- var returnGetNextPageFunction = false;
601
- var restRequestUri = restURL + operatingTable + '/';
602
- var needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
603
- && false === skipPrimaryCheck;
604
- var TABLES = C6.TABLES;
605
- // todo - aggregate primary key check with condition check
606
- // check if PK exists in query, clone so pop does not affect the real data
607
- var primaryKey = (_f = (_e = (_d = structuredClone((_c = TABLES[operatingTable]) === null || _c === void 0 ? void 0 : _c.PRIMARY)) === null || _d === void 0 ? void 0 : _d.pop()) === null || _e === void 0 ? void 0 : _e.split('.')) === null || _f === void 0 ? void 0 : _f.pop();
608
- if (needsConditionOrPrimaryCheck) {
609
- if (undefined === primaryKey) {
610
- if (null === query
611
- || undefined === query
612
- || undefined === (query === null || query === void 0 ? void 0 : query[C6.WHERE])
613
- || (true === Array.isArray(query[C6.WHERE])
614
- || query[C6.WHERE].length === 0)
615
- || (Object.keys(query === null || query === void 0 ? void 0 : query[C6.WHERE]).length === 0)) {
616
- console.error(query);
617
- throw Error('Failed to parse primary key information. Query: (' + JSON.stringify(query) + ') Primary Key: (' + JSON.stringify(primaryKey) + ') TABLES[operatingTable]?.PRIMARY: (' + JSON.stringify((_g = TABLES[operatingTable]) === null || _g === void 0 ? void 0 : _g.PRIMARY) + ') for operatingTable (' + operatingTable + ').');
618
- }
619
- }
620
- else {
621
- if (undefined === query
622
- || null === query
623
- || false === primaryKey in query) {
624
- if (true === request.debug && isDevelopment) {
625
- reactToastify.toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
626
- }
627
- throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
628
- }
629
- if (undefined === (query === null || query === void 0 ? void 0 : query[primaryKey])
630
- || null === (query === null || query === void 0 ? void 0 : query[primaryKey])) {
631
- reactToastify.toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!');
632
- throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
633
- }
634
- }
635
- }
636
- // A part of me exists that wants to remove this, but it's a good feature
637
- // this allows developers the ability to cache requests based on primary key
638
- // for tables like `photos` this can be a huge performance boost
639
- if (undefined !== query
640
- && null !== query
641
- && undefined !== primaryKey
642
- && primaryKey in query) {
643
- restRequestUri += query[primaryKey] + '/';
644
- var removedPkValue_1 = query[primaryKey];
645
- addBackPK = function () {
646
- query !== null && query !== void 0 ? query : (query = {});
647
- query[primaryKey] = removedPkValue_1;
648
- };
649
- delete query[primaryKey];
650
- console.log('query', query, 'primaryKey', primaryKey, 'removedPkValue', removedPkValue_1);
651
- }
652
- else {
653
- console.log('query', query);
654
- }
655
- try {
656
- console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
657
- console.log(request);
658
- 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');
659
- 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');
660
- console.trace();
661
- console.groupEnd();
662
- var axiosActiveRequest = axios[requestMethod.toLowerCase()].apply(axios, tslib.__spreadArray([restRequestUri], ((function () {
663
- // @link - https://axios-http.com/docs/instance
664
- // How configuration vs data is passed is variable, use documentation above for reference
665
- if (requestMethod === GET) {
666
- return [{
667
- withCredentials: withCredentials,
668
- params: query
669
- }];
670
- }
671
- else if (requestMethod === POST) {
672
- if (undefined !== (request === null || request === void 0 ? void 0 : request.dataInsertMultipleRows)) {
673
- return [
674
- request.dataInsertMultipleRows.map(function (data) {
675
- return convertForRequestBody(data, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); });
676
- }),
677
- {
678
- withCredentials: withCredentials,
679
- }
680
- ];
681
- }
682
- return [
683
- convertForRequestBody(query, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); }),
684
- {
685
- withCredentials: withCredentials,
686
- }
687
- ];
688
- }
689
- else if (requestMethod === PUT) {
690
- return [
691
- convertForRequestBody(query, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); }),
692
- {
693
- withCredentials: withCredentials,
694
- }
695
- ];
696
- }
697
- else if (requestMethod === DELETE) {
698
- return [{
699
- withCredentials: withCredentials,
700
- data: convertForRequestBody(query, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); })
701
- }];
702
- }
703
- else {
704
- throw new Error('The request method (' + requestMethod + ') was not recognized.');
705
- }
706
- })()), false));
707
- if (cachingConfirmed) {
708
- // push to cache so we do not repeat the request
709
- apiRequestCache.push({
710
- requestArgumentsSerialized: querySerialized,
711
- request: axiosActiveRequest
712
- });
713
- }
714
- // todo - wip verify this works
715
- // we had removed the value from the request to add to the URI.
716
- addBackPK === null || addBackPK === void 0 ? void 0 : addBackPK(); // adding back so post-processing methods work
717
- // returning the promise with this then is important for tests. todo - we could make that optional.
718
- // https://rapidapi.com/guides/axios-async-await
719
- return axiosActiveRequest.then(function (response) { return tslib.__awaiter(_this, void 0, void 0, function () {
720
- var cacheIndex, responseData_1, fetchDependencies, dependencies_1, fetchReferences_1, apiRequestPromises, _loop_1, _a, _b, _c, _i, tableToFetch;
865
+ return tslib.__awaiter(_this, tslib.__spreadArray([], args_1, true), void 0, function (request) {
866
+ // this could return itself with a new page number, or undefined if the end is reached
867
+ function apiRequest() {
868
+ return tslib.__awaiter(this, void 0, void 0, function () {
869
+ var querySerialized, cacheResult, cachingConfirmed, cacheCheck, cacheCheck, addBackPK, apiResponse, returnGetNextPageFunction, restRequestUri, needsConditionOrPrimaryCheck, TABLES, primaryKey, CarbonSqlExecutor, engine, removedPkValue_1, axiosActiveRequest;
721
870
  var _this = this;
722
- var _d, _e, _f, _g, _h, _j, _k, _l, _m;
723
- return tslib.__generator(this, function (_o) {
724
- switch (_o.label) {
871
+ var _a, _b, _c, _d, _e, _f, _g;
872
+ return tslib.__generator(this, function (_h) {
873
+ switch (_h.label) {
725
874
  case 0:
726
- if (typeof response.data === 'string') {
727
- if (isTest) {
728
- console.trace();
729
- 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 + ')');
730
- }
731
- return [2 /*return*/, Promise.reject(response)];
732
- }
733
- if (cachingConfirmed) {
734
- cacheIndex = apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
735
- apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction;
736
- // only cache get method requests
737
- apiRequestCache[cacheIndex].response = response;
875
+ (_a = request.cacheResults) !== null && _a !== void 0 ? _a : (request.cacheResults = C6.GET === requestMethod);
876
+ if (C6.GET === requestMethod
877
+ && undefined !== ((_b = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _b === void 0 ? void 0 : _b[C6.PAGE])
878
+ && 1 !== query[C6.PAGINATION][C6.PAGE]) {
879
+ console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
880
+ console.log('Request Data (note you may see the success and/or error prompt):', request);
881
+ console.trace();
882
+ console.groupEnd();
738
883
  }
739
- apiResponse = TestRestfulResponse(response, request === null || request === void 0 ? void 0 : request.success, (_d = request === null || request === void 0 ? void 0 : request.error) !== null && _d !== void 0 ? _d : "An unexpected API error occurred!");
740
- if (false === apiResponse) {
884
+ querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
885
+ cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
886
+ cachingConfirmed = false;
887
+ // determine if we need to paginate.
888
+ if (requestMethod === C6.GET) {
889
+ if (undefined === (query === null || query === void 0 ? void 0 : query[C6.PAGINATION])) {
890
+ if (undefined === query || null === query) {
891
+ query = {};
892
+ }
893
+ query[C6.PAGINATION] = {};
894
+ }
895
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
896
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
897
+ // this will evaluate true most the time
898
+ if (true === request.cacheResults) {
899
+ // just find the next, non-fetched, page and return a function to request it
900
+ if (undefined !== cacheResult) {
901
+ do {
902
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, request);
903
+ if (false !== cacheCheck) {
904
+ return [2 /*return*/, cacheCheck];
905
+ }
906
+ // this line incrementing page is why we return recursively
907
+ ++query[C6.PAGINATION][C6.PAGE];
908
+ // this json stringify is to capture the new page number
909
+ querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
910
+ cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
911
+ } while (undefined !== cacheResult);
912
+ if (request.debug && isDevelopment) {
913
+ reactToastify.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);
914
+ }
915
+ // @ts-ignore - this is an incorrect warning on TS, it's well typed
916
+ return [2 /*return*/, apiRequest];
917
+ }
918
+ cachingConfirmed = true;
919
+ }
920
+ else {
921
+ if (request.debug && isDevelopment) {
922
+ reactToastify.toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
923
+ }
924
+ }
741
925
  if (request.debug && isDevelopment) {
742
- reactToastify.toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
926
+ reactToastify.toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
743
927
  }
744
- return [2 /*return*/, response];
745
928
  }
746
- // stateful operations are done in the response callback - its leverages rest generated functions
747
- if (responseCallback) {
748
- responseCallback(response, request, apiResponse);
929
+ else if (request.cacheResults) { // if we are not getting, we are updating, deleting, or inserting
930
+ if (cacheResult) {
931
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, request);
932
+ if (false !== cacheCheck) {
933
+ return [2 /*return*/, cacheCheck];
934
+ }
935
+ }
936
+ cachingConfirmed = true;
937
+ // push to cache so we do not repeat the request
749
938
  }
750
- if (!(C6.GET === requestMethod)) return [3 /*break*/, 6];
751
- responseData_1 = response.data;
752
- returnGetNextPageFunction = 1 !== ((_e = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _e === void 0 ? void 0 : _e[C6.LIMIT]) &&
753
- ((_f = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _f === void 0 ? void 0 : _f[C6.LIMIT]) === responseData_1.rest.length;
754
- if (false === isTest || true === isVerbose) {
755
- console.groupCollapsed('%c API: Response (' + requestMethod + ' ' + tableName + ') returned length (' + ((_g = responseData_1.rest) === null || _g === void 0 ? void 0 : _g.length) + ') of possible (' + ((_h = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _h === void 0 ? void 0 : _h[C6.LIMIT]) + ') limit!', 'color: #0c0');
756
- console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
757
- console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', request);
758
- console.log('%c Response Data:', 'color: #0c0', responseData_1.rest);
759
- console.log('%c Will return get next page function:' + (1 !== ((_j = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _j === void 0 ? void 0 : _j[C6.LIMIT]) ? '' : ' (Will not return with explicit limit 1 set)'), 'color: #0c0', true === returnGetNextPageFunction);
760
- console.trace();
761
- console.groupEnd();
939
+ returnGetNextPageFunction = false;
940
+ restRequestUri = restURL + operatingTable + '/';
941
+ needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
942
+ && false === skipPrimaryCheck;
943
+ TABLES = C6.TABLES;
944
+ primaryKey = (_f = (_e = (_d = structuredClone((_c = TABLES[operatingTable]) === null || _c === void 0 ? void 0 : _c.PRIMARY)) === null || _d === void 0 ? void 0 : _d.pop()) === null || _e === void 0 ? void 0 : _e.split('.')) === null || _f === void 0 ? void 0 : _f.pop();
945
+ if (needsConditionOrPrimaryCheck) {
946
+ if (undefined === primaryKey) {
947
+ if (null === query
948
+ || undefined === query
949
+ || undefined === (query === null || query === void 0 ? void 0 : query[C6.WHERE])
950
+ || (true === Array.isArray(query[C6.WHERE])
951
+ || query[C6.WHERE].length === 0)
952
+ || (Object.keys(query === null || query === void 0 ? void 0 : query[C6.WHERE]).length === 0)) {
953
+ console.error(query);
954
+ throw Error('Failed to parse primary key information. Query: (' + JSON.stringify(query) + ') Primary Key: (' + JSON.stringify(primaryKey) + ') TABLES[operatingTable]?.PRIMARY: (' + JSON.stringify((_g = TABLES[operatingTable]) === null || _g === void 0 ? void 0 : _g.PRIMARY) + ') for operatingTable (' + operatingTable + ').');
955
+ }
956
+ }
957
+ else {
958
+ if (undefined === query
959
+ || null === query
960
+ || false === primaryKey in query) {
961
+ if (true === request.debug && isDevelopment) {
962
+ reactToastify.toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
963
+ }
964
+ throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
965
+ }
966
+ if (undefined === (query === null || query === void 0 ? void 0 : query[primaryKey])
967
+ || null === (query === null || query === void 0 ? void 0 : query[primaryKey])) {
968
+ reactToastify.toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!');
969
+ throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
970
+ }
971
+ }
762
972
  }
763
- if (false === returnGetNextPageFunction
764
- && true === request.debug
765
- && isDevelopment) {
766
- reactToastify.toast.success("DEVS: Response returned length (" + ((_k = responseData_1.rest) === null || _k === void 0 ? void 0 : _k.length) + ") less than limit (" + ((_l = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _l === void 0 ? void 0 : _l[C6.LIMIT]) + ").", toastOptionsDevs);
973
+ if (!(isNode && mysqlPool)) return [3 /*break*/, 2];
974
+ return [4 /*yield*/, Promise.resolve().then(function () { return carbonSqlExecutor; })];
975
+ case 1:
976
+ CarbonSqlExecutor = (_h.sent()).CarbonSqlExecutor;
977
+ engine = new CarbonSqlExecutor(mysqlPool, C6);
978
+ switch (requestMethod) {
979
+ case GET:
980
+ return [2 /*return*/, engine
981
+ .select(tableName, undefined, request)
982
+ .then(function (rows) {
983
+ // mirror the front‐end shape
984
+ var serverResponse = {
985
+ rest: rows,
986
+ session: undefined,
987
+ sql: true,
988
+ };
989
+ return serverResponse;
990
+ })];
991
+ case POST:
992
+ return [2 /*return*/, engine
993
+ .insert(tableName, request)
994
+ .then(function (created) { return ({
995
+ rest: created,
996
+ }); })];
997
+ case PUT:
998
+ return [2 /*return*/, engine
999
+ .update(tableName, undefined, request)
1000
+ .then(function (updatedResult) {
1001
+ var _a;
1002
+ return ({
1003
+ rest: updatedResult,
1004
+ rowCount: (_a = updatedResult.affectedRows) !== null && _a !== void 0 ? _a : 0,
1005
+ });
1006
+ })];
1007
+ case DELETE:
1008
+ return [2 /*return*/, engine
1009
+ .delete(tableName, undefined, request)
1010
+ .then(function (deletedResult) {
1011
+ var _a;
1012
+ return ({
1013
+ rest: deletedResult,
1014
+ rowCount: (_a = deletedResult.affectedRows) !== null && _a !== void 0 ? _a : 0,
1015
+ deleted: true,
1016
+ });
1017
+ })];
1018
+ default:
1019
+ throw new Error("Unsupported method: ".concat(requestMethod));
767
1020
  }
768
- (_m = request.fetchDependencies) !== null && _m !== void 0 ? _m : (request.fetchDependencies = exports.eFetchDependencies.NONE);
769
- if (!(request.fetchDependencies
770
- && 'number' === typeof request.fetchDependencies
771
- && responseData_1.rest.length > 0)) return [3 /*break*/, 6];
772
- fetchDependencies = request.fetchDependencies;
773
- console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
774
- + (fetchDependencies & exports.eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
775
- + (fetchDependencies & exports.eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
776
- + (fetchDependencies & exports.eFetchDependencies.C6ENTITY ? ' | (C6ENTITY)' : '')
777
- + (fetchDependencies & exports.eFetchDependencies.RECURSIVE ? ' | (RECURSIVE)' : ''), 'color: #33ccff');
778
- console.groupCollapsed('Collapsed JS Trace');
779
- console.trace(); // hidden in collapsed group
780
- console.groupEnd();
781
- dependencies_1 = {};
782
- if (fetchDependencies & exports.eFetchDependencies.C6ENTITY) {
783
- dependencies_1 = operatingTable.endsWith("carbon_carbons")
784
- ? tslib.__assign(tslib.__assign({}, fetchDependencies & exports.eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
785
- ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
786
- : {}), fetchDependencies & exports.eFetchDependencies.PARENTS // REFERENCES === PARENTS
787
- ? C6.TABLES[operatingTable].TABLE_REFERENCES
788
- : {}) : tslib.__assign(tslib.__assign({}, fetchDependencies & exports.eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
789
- ? tslib.__assign(tslib.__assign({}, Object.keys(C6.TABLES[operatingTable].TABLE_REFERENCES).reduce(function (accumulator, columnName) {
790
- if (!C6.TABLES[operatingTable].PRIMARY_SHORT.includes(columnName)) {
791
- accumulator[columnName] = C6.TABLES[operatingTable].TABLE_REFERENCES[columnName];
792
- }
793
- return accumulator;
794
- }, {})), C6.TABLES[operatingTable].TABLE_REFERENCED_BY // it is unlikely that a C6 table will have any TABLE_REFERENCED_BY
795
- ) : {}), fetchDependencies & exports.eFetchDependencies.PARENTS // REFERENCES === PARENTS
796
- ? C6.TABLES[operatingTable].PRIMARY_SHORT.reduce(function (accumulator, primaryKey) {
797
- if (primaryKey in C6.TABLES[operatingTable].TABLE_REFERENCES) {
798
- accumulator[primaryKey] = C6.TABLES[operatingTable].TABLE_REFERENCES[primaryKey];
799
- }
800
- return accumulator;
801
- }, {})
802
- : {});
1021
+ case 2:
1022
+ // A part of me exists that wants to remove this, but it's a good feature
1023
+ // this allows developers the ability to cache requests based on primary key
1024
+ // for tables like `photos` this can be a huge performance boost
1025
+ if (undefined !== query
1026
+ && null !== query
1027
+ && undefined !== primaryKey
1028
+ && primaryKey in query) {
1029
+ restRequestUri += query[primaryKey] + '/';
1030
+ removedPkValue_1 = query[primaryKey];
1031
+ addBackPK = function () {
1032
+ query !== null && query !== void 0 ? query : (query = {});
1033
+ query[primaryKey] = removedPkValue_1;
1034
+ };
1035
+ delete query[primaryKey];
1036
+ console.log('query', query, 'primaryKey', primaryKey, 'removedPkValue', removedPkValue_1);
803
1037
  }
804
1038
  else {
805
- // this is the natural mysql context
806
- dependencies_1 = tslib.__assign(tslib.__assign({}, fetchDependencies & exports.eFetchDependencies.REFERENCED // REFERENCED === CHILDREN
807
- ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
808
- : {}), fetchDependencies & exports.eFetchDependencies.REFERENCES // REFERENCES === PARENTS
809
- ? C6.TABLES[operatingTable].TABLE_REFERENCES
810
- : {});
1039
+ console.log('query', query);
811
1040
  }
812
- fetchReferences_1 = {};
813
- apiRequestPromises = [];
814
- console.log('%c Dependencies', 'color: #005555', dependencies_1);
815
- Object.keys(dependencies_1)
816
- .forEach(function (column) { return dependencies_1[column]
817
- .forEach(function (constraint) {
818
- var _a, _b, _c, _d;
819
- var _e, _f, _g;
820
- var columnValues = (_b = (_a = responseData_1.rest[column]) !== null && _a !== void 0 ? _a : responseData_1.rest.map(function (row) {
821
- if (operatingTable.endsWith("carbons")
822
- && 'entity_tag' in row
823
- && !constraint.TABLE.endsWith(row['entity_tag'].split('\\').pop().toLowerCase())) {
824
- return false; // map
825
- }
826
- if (!(column in row)) {
827
- return false;
1041
+ try {
1042
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
1043
+ console.log(request);
1044
+ 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');
1045
+ 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');
1046
+ console.trace();
1047
+ console.groupEnd();
1048
+ axiosActiveRequest = axios[requestMethod.toLowerCase()].apply(axios, tslib.__spreadArray([restRequestUri], ((function () {
1049
+ // @link - https://axios-http.com/docs/instance
1050
+ // How configuration vs data is passed is variable, use documentation above for reference
1051
+ if (requestMethod === GET) {
1052
+ return [{
1053
+ withCredentials: withCredentials,
1054
+ params: query
1055
+ }];
828
1056
  }
829
- // todo - row[column] is a FK value, we should optionally remove values that are already in state
830
- // this could be any column in the table constraint.TABLE, not just the primary key
831
- return row[column];
832
- }).filter(function (n) { return n; })) !== null && _b !== void 0 ? _b : [];
833
- if (columnValues.length === 0) {
834
- return; // forEach
835
- }
836
- (_c = fetchReferences_1[_e = constraint.TABLE]) !== null && _c !== void 0 ? _c : (fetchReferences_1[_e] = {});
837
- (_d = (_f = fetchReferences_1[constraint.TABLE])[_g = constraint.COLUMN]) !== null && _d !== void 0 ? _d : (_f[_g] = []);
838
- fetchReferences_1[constraint.TABLE][constraint.COLUMN].push(columnValues);
839
- }); });
840
- console.log('fetchReferences', fetchReferences_1);
841
- _loop_1 = function (tableToFetch) {
842
- var referencesTables, shouldContinue, fetchTable, RestApi, nextFetchDependencies;
843
- var _p;
844
- return tslib.__generator(this, function (_q) {
845
- switch (_q.label) {
846
- case 0:
847
- if (fetchDependencies & exports.eFetchDependencies.C6ENTITY
848
- && 'string' === typeof tableName
849
- && tableName.endsWith("carbon_carbons")) {
850
- referencesTables = responseData_1.rest.reduce(function (accumulator, row) {
851
- if ('entity_tag' in row && !accumulator.includes(row['entity_tag'])) {
852
- accumulator.push(row['entity_tag']);
853
- }
854
- return accumulator;
855
- }, []).map(function (entityTag) { return entityTag.split('\\').pop().toLowerCase(); });
856
- shouldContinue = referencesTables.find(function (referencesTable) { return tableToFetch.endsWith(referencesTable); });
857
- if (!shouldContinue) {
858
- console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables);
859
- return [2 /*return*/, "continue"];
860
- }
861
- console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') will be fetched.', 'color: #0c0');
862
- }
863
- return [4 /*yield*/, C6.IMPORT(tableToFetch)];
864
- case 1:
865
- fetchTable = _q.sent();
866
- RestApi = fetchTable.default;
867
- console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff');
868
- nextFetchDependencies = exports.eFetchDependencies.NONE;
869
- if (fetchDependencies & exports.eFetchDependencies.RECURSIVE) {
870
- if (fetchDependencies & exports.eFetchDependencies.ALL) {
871
- 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.');
872
- }
873
- nextFetchDependencies = fetchDependencies;
874
- }
875
- else if (fetchDependencies & exports.eFetchDependencies.C6ENTITY) {
876
- if (tableToFetch === "carbon_carbons") {
877
- nextFetchDependencies = fetchDependencies;
878
- }
879
- else {
880
- nextFetchDependencies = fetchDependencies ^ exports.eFetchDependencies.C6ENTITY;
1057
+ else if (requestMethod === POST) {
1058
+ if (undefined !== (request === null || request === void 0 ? void 0 : request.dataInsertMultipleRows)) {
1059
+ return [
1060
+ request.dataInsertMultipleRows.map(function (data) {
1061
+ return convertForRequestBody(data, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); });
1062
+ }),
1063
+ {
1064
+ withCredentials: withCredentials,
881
1065
  }
1066
+ ];
1067
+ }
1068
+ return [
1069
+ convertForRequestBody(query, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); }),
1070
+ {
1071
+ withCredentials: withCredentials,
882
1072
  }
883
- console.log('fetchReferences', fetchReferences_1[tableToFetch], "Current fetchDependencies for (" + operatingTable + "):", fetchDependencies, "New fetchDependencies for (" + tableToFetch + "): ", nextFetchDependencies);
884
- // 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
885
- // it not certain that they are using carbons' entities either
886
- // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
887
- // todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
888
- apiRequestPromises.push(RestApi.Get((_p = {},
889
- _p[C6.WHERE] = {
890
- 0: Object.keys(fetchReferences_1[tableToFetch]).reduce(function (sum, column) {
891
- fetchReferences_1[tableToFetch][column] = fetchReferences_1[tableToFetch][column].flat(Infinity);
892
- if (0 === fetchReferences_1[tableToFetch][column].length) {
893
- console.warn('The column (' + column + ') was not found in the response data. We will not fetch.', responseData_1);
894
- return false;
895
- }
896
- sum[column] = fetchReferences_1[tableToFetch][column].length === 1
897
- ? fetchReferences_1[tableToFetch][column][0]
898
- : [
899
- C6.IN, fetchReferences_1[tableToFetch][column]
900
- ];
901
- return sum;
902
- }, {})
903
- },
904
- _p.fetchDependencies = nextFetchDependencies,
905
- _p)));
906
- return [2 /*return*/];
1073
+ ];
907
1074
  }
908
- });
909
- };
910
- _a = fetchReferences_1;
911
- _b = [];
912
- for (_c in _a)
913
- _b.push(_c);
914
- _i = 0;
915
- _o.label = 1;
916
- case 1:
917
- if (!(_i < _b.length)) return [3 /*break*/, 4];
918
- _c = _b[_i];
919
- if (!(_c in _a)) return [3 /*break*/, 3];
920
- tableToFetch = _c;
921
- return [5 /*yield**/, _loop_1(tableToFetch)];
922
- case 2:
923
- _o.sent();
924
- _o.label = 3;
925
- case 3:
926
- _i++;
927
- return [3 /*break*/, 1];
928
- case 4:
929
- console.groupEnd();
930
- return [4 /*yield*/, Promise.all(apiRequestPromises)];
931
- case 5:
932
- _o.sent();
933
- apiRequestPromises.map(function (promise) { return tslib.__awaiter(_this, void 0, void 0, function () {
934
- var _a, _b;
935
- return tslib.__generator(this, function (_c) {
936
- switch (_c.label) {
937
- case 0:
938
- if (!Array.isArray(request.fetchDependencies)) {
939
- request.fetchDependencies = [];
1075
+ else if (requestMethod === PUT) {
1076
+ return [
1077
+ convertForRequestBody(query, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); }),
1078
+ {
1079
+ withCredentials: withCredentials,
940
1080
  }
941
- _b = (_a = request.fetchDependencies).push;
942
- return [4 /*yield*/, promise];
943
- case 1:
944
- _b.apply(_a, [_c.sent()]);
945
- return [2 /*return*/];
1081
+ ];
1082
+ }
1083
+ else if (requestMethod === DELETE) {
1084
+ return [{
1085
+ withCredentials: withCredentials,
1086
+ data: convertForRequestBody(query, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); })
1087
+ }];
946
1088
  }
947
- });
948
- }); });
949
- _o.label = 6;
950
- case 6:
951
- if (request.debug && isDevelopment) {
952
- reactToastify.toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1089
+ else {
1090
+ throw new Error('The request method (' + requestMethod + ') was not recognized.');
1091
+ }
1092
+ })()), false));
1093
+ if (cachingConfirmed) {
1094
+ // push to cache so we do not repeat the request
1095
+ apiRequestCache.push({
1096
+ requestArgumentsSerialized: querySerialized,
1097
+ request: axiosActiveRequest
1098
+ });
1099
+ }
1100
+ // todo - wip verify this works
1101
+ // we had removed the value from the request to add to the URI.
1102
+ addBackPK === null || addBackPK === void 0 ? void 0 : addBackPK(); // adding back so post-processing methods work
1103
+ // returning the promise with this then is important for tests. todo - we could make that optional.
1104
+ // https://rapidapi.com/guides/axios-async-await
1105
+ return [2 /*return*/, axiosActiveRequest.then(function (response) { return tslib.__awaiter(_this, void 0, void 0, function () {
1106
+ var cacheIndex, responseData_1, fetchDependencies, dependencies_1, fetchReferences_1, apiRequestPromises, _loop_1, _a, _b, _c, _i, tableToFetch;
1107
+ var _this = this;
1108
+ var _d, _e, _f, _g, _h, _j, _k, _l, _m;
1109
+ return tslib.__generator(this, function (_o) {
1110
+ switch (_o.label) {
1111
+ case 0:
1112
+ if (typeof response.data === 'string') {
1113
+ if (isTest) {
1114
+ console.trace();
1115
+ 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 + ')');
1116
+ }
1117
+ return [2 /*return*/, Promise.reject(response)];
1118
+ }
1119
+ if (cachingConfirmed) {
1120
+ cacheIndex = apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
1121
+ apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction;
1122
+ // only cache get method requests
1123
+ apiRequestCache[cacheIndex].response = response;
1124
+ }
1125
+ apiResponse = TestRestfulResponse(response, request === null || request === void 0 ? void 0 : request.success, (_d = request === null || request === void 0 ? void 0 : request.error) !== null && _d !== void 0 ? _d : "An unexpected API error occurred!");
1126
+ if (false === apiResponse) {
1127
+ if (request.debug && isDevelopment) {
1128
+ reactToastify.toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
1129
+ }
1130
+ return [2 /*return*/, response];
1131
+ }
1132
+ // stateful operations are done in the response callback - its leverages rest generated functions
1133
+ if (responseCallback) {
1134
+ responseCallback(response, request, apiResponse);
1135
+ }
1136
+ if (!(C6.GET === requestMethod)) return [3 /*break*/, 6];
1137
+ responseData_1 = response.data;
1138
+ returnGetNextPageFunction = 1 !== ((_e = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _e === void 0 ? void 0 : _e[C6.LIMIT]) &&
1139
+ ((_f = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _f === void 0 ? void 0 : _f[C6.LIMIT]) === responseData_1.rest.length;
1140
+ if (false === isTest || true === isVerbose) {
1141
+ console.groupCollapsed('%c API: Response (' + requestMethod + ' ' + tableName + ') returned length (' + ((_g = responseData_1.rest) === null || _g === void 0 ? void 0 : _g.length) + ') of possible (' + ((_h = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _h === void 0 ? void 0 : _h[C6.LIMIT]) + ') limit!', 'color: #0c0');
1142
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
1143
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', request);
1144
+ console.log('%c Response Data:', 'color: #0c0', responseData_1.rest);
1145
+ console.log('%c Will return get next page function:' + (1 !== ((_j = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _j === void 0 ? void 0 : _j[C6.LIMIT]) ? '' : ' (Will not return with explicit limit 1 set)'), 'color: #0c0', true === returnGetNextPageFunction);
1146
+ console.trace();
1147
+ console.groupEnd();
1148
+ }
1149
+ if (false === returnGetNextPageFunction
1150
+ && true === request.debug
1151
+ && isDevelopment) {
1152
+ reactToastify.toast.success("DEVS: Response returned length (" + ((_k = responseData_1.rest) === null || _k === void 0 ? void 0 : _k.length) + ") less than limit (" + ((_l = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _l === void 0 ? void 0 : _l[C6.LIMIT]) + ").", toastOptionsDevs);
1153
+ }
1154
+ (_m = request.fetchDependencies) !== null && _m !== void 0 ? _m : (request.fetchDependencies = exports.eFetchDependencies.NONE);
1155
+ if (!(request.fetchDependencies
1156
+ && 'number' === typeof request.fetchDependencies
1157
+ && responseData_1.rest.length > 0)) return [3 /*break*/, 6];
1158
+ fetchDependencies = request.fetchDependencies;
1159
+ console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
1160
+ + (fetchDependencies & exports.eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
1161
+ + (fetchDependencies & exports.eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
1162
+ + (fetchDependencies & exports.eFetchDependencies.C6ENTITY ? ' | (C6ENTITY)' : '')
1163
+ + (fetchDependencies & exports.eFetchDependencies.RECURSIVE ? ' | (RECURSIVE)' : ''), 'color: #33ccff');
1164
+ console.groupCollapsed('Collapsed JS Trace');
1165
+ console.trace(); // hidden in collapsed group
1166
+ console.groupEnd();
1167
+ dependencies_1 = {};
1168
+ if (fetchDependencies & exports.eFetchDependencies.C6ENTITY) {
1169
+ dependencies_1 = operatingTable.endsWith("carbon_carbons")
1170
+ ? tslib.__assign(tslib.__assign({}, fetchDependencies & exports.eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
1171
+ ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1172
+ : {}), fetchDependencies & exports.eFetchDependencies.PARENTS // REFERENCES === PARENTS
1173
+ ? C6.TABLES[operatingTable].TABLE_REFERENCES
1174
+ : {}) : tslib.__assign(tslib.__assign({}, fetchDependencies & exports.eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
1175
+ ? tslib.__assign(tslib.__assign({}, Object.keys(C6.TABLES[operatingTable].TABLE_REFERENCES).reduce(function (accumulator, columnName) {
1176
+ if (!C6.TABLES[operatingTable].PRIMARY_SHORT.includes(columnName)) {
1177
+ accumulator[columnName] = C6.TABLES[operatingTable].TABLE_REFERENCES[columnName];
1178
+ }
1179
+ return accumulator;
1180
+ }, {})), C6.TABLES[operatingTable].TABLE_REFERENCED_BY // it is unlikely that a C6 table will have any TABLE_REFERENCED_BY
1181
+ ) : {}), fetchDependencies & exports.eFetchDependencies.PARENTS // REFERENCES === PARENTS
1182
+ ? C6.TABLES[operatingTable].PRIMARY_SHORT.reduce(function (accumulator, primaryKey) {
1183
+ if (primaryKey in C6.TABLES[operatingTable].TABLE_REFERENCES) {
1184
+ accumulator[primaryKey] = C6.TABLES[operatingTable].TABLE_REFERENCES[primaryKey];
1185
+ }
1186
+ return accumulator;
1187
+ }, {})
1188
+ : {});
1189
+ }
1190
+ else {
1191
+ // this is the natural mysql context
1192
+ dependencies_1 = tslib.__assign(tslib.__assign({}, fetchDependencies & exports.eFetchDependencies.REFERENCED // REFERENCED === CHILDREN
1193
+ ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1194
+ : {}), fetchDependencies & exports.eFetchDependencies.REFERENCES // REFERENCES === PARENTS
1195
+ ? C6.TABLES[operatingTable].TABLE_REFERENCES
1196
+ : {});
1197
+ }
1198
+ fetchReferences_1 = {};
1199
+ apiRequestPromises = [];
1200
+ console.log('%c Dependencies', 'color: #005555', dependencies_1);
1201
+ Object.keys(dependencies_1)
1202
+ .forEach(function (column) { return dependencies_1[column]
1203
+ .forEach(function (constraint) {
1204
+ var _a, _b, _c, _d;
1205
+ var _e, _f, _g;
1206
+ var columnValues = (_b = (_a = responseData_1.rest[column]) !== null && _a !== void 0 ? _a : responseData_1.rest.map(function (row) {
1207
+ if (operatingTable.endsWith("carbons")
1208
+ && 'entity_tag' in row
1209
+ && !constraint.TABLE.endsWith(row['entity_tag'].split('\\').pop().toLowerCase())) {
1210
+ return false; // map
1211
+ }
1212
+ if (!(column in row)) {
1213
+ return false;
1214
+ }
1215
+ // todo - row[column] is a FK value, we should optionally remove values that are already in state
1216
+ // this could be any column in the table constraint.TABLE, not just the primary key
1217
+ return row[column];
1218
+ }).filter(function (n) { return n; })) !== null && _b !== void 0 ? _b : [];
1219
+ if (columnValues.length === 0) {
1220
+ return; // forEach
1221
+ }
1222
+ (_c = fetchReferences_1[_e = constraint.TABLE]) !== null && _c !== void 0 ? _c : (fetchReferences_1[_e] = {});
1223
+ (_d = (_f = fetchReferences_1[constraint.TABLE])[_g = constraint.COLUMN]) !== null && _d !== void 0 ? _d : (_f[_g] = []);
1224
+ fetchReferences_1[constraint.TABLE][constraint.COLUMN].push(columnValues);
1225
+ }); });
1226
+ console.log('fetchReferences', fetchReferences_1);
1227
+ _loop_1 = function (tableToFetch) {
1228
+ var referencesTables, shouldContinue, fetchTable, RestApi, nextFetchDependencies;
1229
+ var _p;
1230
+ return tslib.__generator(this, function (_q) {
1231
+ switch (_q.label) {
1232
+ case 0:
1233
+ if (fetchDependencies & exports.eFetchDependencies.C6ENTITY
1234
+ && 'string' === typeof tableName
1235
+ && tableName.endsWith("carbon_carbons")) {
1236
+ referencesTables = responseData_1.rest.reduce(function (accumulator, row) {
1237
+ if ('entity_tag' in row && !accumulator.includes(row['entity_tag'])) {
1238
+ accumulator.push(row['entity_tag']);
1239
+ }
1240
+ return accumulator;
1241
+ }, []).map(function (entityTag) { return entityTag.split('\\').pop().toLowerCase(); });
1242
+ shouldContinue = referencesTables.find(function (referencesTable) { return tableToFetch.endsWith(referencesTable); });
1243
+ if (!shouldContinue) {
1244
+ console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables);
1245
+ return [2 /*return*/, "continue"];
1246
+ }
1247
+ console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') will be fetched.', 'color: #0c0');
1248
+ }
1249
+ return [4 /*yield*/, C6.IMPORT(tableToFetch)];
1250
+ case 1:
1251
+ fetchTable = _q.sent();
1252
+ RestApi = fetchTable.default;
1253
+ console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff');
1254
+ nextFetchDependencies = exports.eFetchDependencies.NONE;
1255
+ if (fetchDependencies & exports.eFetchDependencies.RECURSIVE) {
1256
+ if (fetchDependencies & exports.eFetchDependencies.ALL) {
1257
+ 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.');
1258
+ }
1259
+ nextFetchDependencies = fetchDependencies;
1260
+ }
1261
+ else if (fetchDependencies & exports.eFetchDependencies.C6ENTITY) {
1262
+ if (tableToFetch === "carbon_carbons") {
1263
+ nextFetchDependencies = fetchDependencies;
1264
+ }
1265
+ else {
1266
+ nextFetchDependencies = fetchDependencies ^ exports.eFetchDependencies.C6ENTITY;
1267
+ }
1268
+ }
1269
+ console.log('fetchReferences', fetchReferences_1[tableToFetch], "Current fetchDependencies for (" + operatingTable + "):", fetchDependencies, "New fetchDependencies for (" + tableToFetch + "): ", nextFetchDependencies);
1270
+ // 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
1271
+ // it not certain that they are using carbons' entities either
1272
+ // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
1273
+ // todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
1274
+ apiRequestPromises.push(RestApi.Get((_p = {},
1275
+ _p[C6.WHERE] = {
1276
+ 0: Object.keys(fetchReferences_1[tableToFetch]).reduce(function (sum, column) {
1277
+ fetchReferences_1[tableToFetch][column] = fetchReferences_1[tableToFetch][column].flat(Infinity);
1278
+ if (0 === fetchReferences_1[tableToFetch][column].length) {
1279
+ console.warn('The column (' + column + ') was not found in the response data. We will not fetch.', responseData_1);
1280
+ return false;
1281
+ }
1282
+ sum[column] = fetchReferences_1[tableToFetch][column].length === 1
1283
+ ? fetchReferences_1[tableToFetch][column][0]
1284
+ : [
1285
+ C6.IN, fetchReferences_1[tableToFetch][column]
1286
+ ];
1287
+ return sum;
1288
+ }, {})
1289
+ },
1290
+ _p.fetchDependencies = nextFetchDependencies,
1291
+ _p)));
1292
+ return [2 /*return*/];
1293
+ }
1294
+ });
1295
+ };
1296
+ _a = fetchReferences_1;
1297
+ _b = [];
1298
+ for (_c in _a)
1299
+ _b.push(_c);
1300
+ _i = 0;
1301
+ _o.label = 1;
1302
+ case 1:
1303
+ if (!(_i < _b.length)) return [3 /*break*/, 4];
1304
+ _c = _b[_i];
1305
+ if (!(_c in _a)) return [3 /*break*/, 3];
1306
+ tableToFetch = _c;
1307
+ return [5 /*yield**/, _loop_1(tableToFetch)];
1308
+ case 2:
1309
+ _o.sent();
1310
+ _o.label = 3;
1311
+ case 3:
1312
+ _i++;
1313
+ return [3 /*break*/, 1];
1314
+ case 4:
1315
+ console.groupEnd();
1316
+ return [4 /*yield*/, Promise.all(apiRequestPromises)];
1317
+ case 5:
1318
+ _o.sent();
1319
+ apiRequestPromises.map(function (promise) { return tslib.__awaiter(_this, void 0, void 0, function () {
1320
+ var _a, _b;
1321
+ return tslib.__generator(this, function (_c) {
1322
+ switch (_c.label) {
1323
+ case 0:
1324
+ if (!Array.isArray(request.fetchDependencies)) {
1325
+ request.fetchDependencies = [];
1326
+ }
1327
+ _b = (_a = request.fetchDependencies).push;
1328
+ return [4 /*yield*/, promise];
1329
+ case 1:
1330
+ _b.apply(_a, [_c.sent()]);
1331
+ return [2 /*return*/];
1332
+ }
1333
+ });
1334
+ }); });
1335
+ _o.label = 6;
1336
+ case 6:
1337
+ if (request.debug && isDevelopment) {
1338
+ reactToastify.toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1339
+ }
1340
+ return [2 /*return*/, response];
1341
+ }
1342
+ });
1343
+ }); })];
953
1344
  }
954
- return [2 /*return*/, response];
1345
+ catch (error) {
1346
+ if (isTest) {
1347
+ throw new Error(JSON.stringify(error));
1348
+ }
1349
+ console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
1350
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
1351
+ console.warn(error);
1352
+ console.trace();
1353
+ console.groupEnd();
1354
+ TestRestfulResponse(error, request === null || request === void 0 ? void 0 : request.success, (request === null || request === void 0 ? void 0 : request.error) || "An restful API error occurred!");
1355
+ return [2 /*return*/, null];
1356
+ }
1357
+ return [2 /*return*/];
955
1358
  }
956
1359
  });
957
- }); });
1360
+ });
958
1361
  }
959
- catch (error) {
960
- if (isTest) {
961
- throw new Error(JSON.stringify(error));
1362
+ var query;
1363
+ if (request === void 0) { request = {}; }
1364
+ return tslib.__generator(this, function (_a) {
1365
+ switch (_a.label) {
1366
+ case 0:
1367
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request for (' + operatingTable + ')', 'color: #0c0');
1368
+ console.log('request', request);
1369
+ console.groupEnd();
1370
+ if ('function' === typeof queryCallback) {
1371
+ query = queryCallback(request); // obj or obj[]
1372
+ }
1373
+ else {
1374
+ query = queryCallback;
1375
+ }
1376
+ if (undefined === query || null === query) {
1377
+ if (request.debug && isDevelopment) {
1378
+ reactToastify.toast.warning("DEV: queryCallback returned undefined, signaling in Custom Cache. (returning null)", toastOptionsDevs);
1379
+ }
1380
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') undefined, returning null (will not fire ajax)!', 'color: #c00');
1381
+ 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');
1382
+ console.trace();
1383
+ console.groupEnd();
1384
+ return [2 /*return*/, null];
1385
+ }
1386
+ if (C6.GET === requestMethod) {
1387
+ if (undefined === query[C6.PAGINATION]) {
1388
+ query[C6.PAGINATION] = {};
1389
+ }
1390
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
1391
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
1392
+ }
1393
+ return [4 /*yield*/, apiRequest()];
1394
+ case 1: return [2 /*return*/, _a.sent()];
962
1395
  }
963
- console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
964
- console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
965
- console.warn(error);
966
- console.trace();
967
- console.groupEnd();
968
- TestRestfulResponse(error, request === null || request === void 0 ? void 0 : request.success, (request === null || request === void 0 ? void 0 : request.error) || "An restful API error occurred!");
969
- return null;
970
- }
971
- }
972
- return apiRequest();
1396
+ });
1397
+ });
973
1398
  };
974
1399
  }
975
1400
 
@@ -988,6 +1413,7 @@ function timeout(shouldContinueAfterTimeout, cb, timeoutMs) {
988
1413
  }
989
1414
 
990
1415
  exports.C6Constants = C6Constants;
1416
+ exports.CarbonSqlExecutor = CarbonSqlExecutor;
991
1417
  exports.DELETE = DELETE;
992
1418
  exports.GET = GET;
993
1419
  exports.POST = POST;
@@ -1000,6 +1426,7 @@ exports.convertForRequestBody = convertForRequestBody;
1000
1426
  exports.extendedTypeHints = extendedTypeHints;
1001
1427
  exports.getEnvVar = getEnvVar;
1002
1428
  exports.isLocal = isDevelopment;
1429
+ exports.isNode = isNode;
1003
1430
  exports.isPromise = isPromise;
1004
1431
  exports.isTest = isTest;
1005
1432
  exports.isVerbose = isVerbose;