@carbonorm/carbonnode 3.0.0 → 3.0.2

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 (47) hide show
  1. package/dist/api/builders/sqlBuilder.d.ts +3 -0
  2. package/dist/api/convertForRequestBody.d.ts +1 -1
  3. package/dist/api/executors/Executor.d.ts +16 -0
  4. package/dist/api/executors/HttpExecutor.d.ts +13 -0
  5. package/dist/api/executors/SqlExecutor.d.ts +19 -0
  6. package/dist/api/restRequest.d.ts +9 -166
  7. package/dist/api/types/dynamicFetching.d.ts +10 -0
  8. package/dist/api/types/modifyTypes.d.ts +9 -0
  9. package/dist/api/types/mysqlTypes.d.ts +4 -0
  10. package/dist/api/types/ormInterfaces.d.ts +219 -0
  11. package/dist/api/utils/apiHelpers.d.ts +9 -0
  12. package/dist/api/utils/cacheManager.d.ts +10 -0
  13. package/dist/api/utils/determineRuntimeJsType.d.ts +5 -0
  14. package/dist/api/utils/logger.d.ts +7 -0
  15. package/dist/api/utils/sortAndSerializeQueryObject.d.ts +1 -0
  16. package/dist/api/utils/testHelpers.d.ts +1 -0
  17. package/dist/api/utils/toastNotifier.d.ts +2 -0
  18. package/dist/index.cjs.js +665 -614
  19. package/dist/index.cjs.js.map +1 -1
  20. package/dist/index.d.ts +15 -2
  21. package/dist/index.esm.js +655 -618
  22. package/dist/index.esm.js.map +1 -1
  23. package/package.json +22 -6
  24. package/scripts/assets/handlebars/C6.ts.handlebars +13 -5
  25. package/scripts/assets/handlebars/Table.ts.handlebars +44 -12
  26. package/scripts/generateRestBindings.cjs +1 -1
  27. package/scripts/generateRestBindings.ts +1 -1
  28. package/src/api/builders/sqlBuilder.ts +173 -0
  29. package/src/api/convertForRequestBody.ts +2 -3
  30. package/src/api/executors/Executor.ts +28 -0
  31. package/src/api/executors/HttpExecutor.ts +794 -0
  32. package/src/api/executors/SqlExecutor.ts +104 -0
  33. package/src/api/restRequest.ts +50 -1287
  34. package/src/api/types/dynamicFetching.ts +10 -0
  35. package/src/api/types/modifyTypes.ts +25 -0
  36. package/src/api/types/mysqlTypes.ts +33 -0
  37. package/src/api/types/ormInterfaces.ts +310 -0
  38. package/src/api/utils/apiHelpers.ts +82 -0
  39. package/src/api/utils/cacheManager.ts +67 -0
  40. package/src/api/utils/determineRuntimeJsType.ts +46 -0
  41. package/src/api/utils/logger.ts +24 -0
  42. package/src/api/utils/sortAndSerializeQueryObject.ts +12 -0
  43. package/src/api/utils/testHelpers.ts +24 -0
  44. package/src/api/utils/toastNotifier.ts +11 -0
  45. package/src/index.ts +15 -2
  46. package/src/api/carbonSqlExecutor.ts +0 -279
  47. package/src/api/interfaces/ormInterfaces.ts +0 -87
package/dist/index.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import axios from 'axios';
2
2
  import Qs from 'qs';
3
- import { __awaiter, __generator, __assign, __spreadArray } from 'tslib';
3
+ import { __assign, __awaiter, __spreadArray, __generator, __extends } from 'tslib';
4
4
  import { toast } from 'react-toastify';
5
5
 
6
6
  var C6Constants = {
@@ -232,366 +232,6 @@ var axiosInstance = (axios.create({
232
232
  */
233
233
  }));
234
234
 
235
- // import { validatePayloadAgainstSchema } from './validator'; // C6 schema validator
236
- var CarbonSqlExecutor = /** @class */ (function () {
237
- function CarbonSqlExecutor(pool, C6) {
238
- this.pool = pool;
239
- this.C6 = C6;
240
- }
241
- CarbonSqlExecutor.prototype.withConnection = function (cb) {
242
- return __awaiter(this, void 0, void 0, function () {
243
- var conn;
244
- return __generator(this, function (_a) {
245
- switch (_a.label) {
246
- case 0: return [4 /*yield*/, this.pool.getConnection()];
247
- case 1:
248
- conn = _a.sent();
249
- _a.label = 2;
250
- case 2:
251
- _a.trys.push([2, , 4, 5]);
252
- return [4 /*yield*/, cb(conn)];
253
- case 3: return [2 /*return*/, _a.sent()];
254
- case 4:
255
- conn.release();
256
- return [7 /*endfinally*/];
257
- case 5: return [2 /*return*/];
258
- }
259
- });
260
- });
261
- };
262
- CarbonSqlExecutor.prototype.handle = function (req, res, next) {
263
- return __awaiter(this, void 0, void 0, function () {
264
- var method, table, primary, payload, result, _a, err_1;
265
- return __generator(this, function (_b) {
266
- switch (_b.label) {
267
- case 0:
268
- _b.trys.push([0, 11, , 12]);
269
- method = req.method.toUpperCase();
270
- table = req.params.table;
271
- primary = req.params.primary;
272
- payload = method === 'GET' ? req.query : req.body;
273
- if (!(table in this.C6.TABLES)) {
274
- res.status(400).json({ error: "Invalid table: ".concat(table) });
275
- return [2 /*return*/];
276
- }
277
- result = void 0;
278
- _a = method;
279
- switch (_a) {
280
- case 'GET': return [3 /*break*/, 1];
281
- case 'OPTIONS': return [3 /*break*/, 1];
282
- case 'POST': return [3 /*break*/, 3];
283
- case 'PUT': return [3 /*break*/, 5];
284
- case 'DELETE': return [3 /*break*/, 7];
285
- }
286
- return [3 /*break*/, 9];
287
- case 1: return [4 /*yield*/, this.select(table, primary, payload)];
288
- case 2:
289
- result = _b.sent();
290
- return [3 /*break*/, 10];
291
- case 3: return [4 /*yield*/, this.insert(table, payload)];
292
- case 4:
293
- result = _b.sent();
294
- return [3 /*break*/, 10];
295
- case 5: return [4 /*yield*/, this.update(table, primary, payload)];
296
- case 6:
297
- result = _b.sent();
298
- return [3 /*break*/, 10];
299
- case 7: return [4 /*yield*/, this.delete(table, primary, payload)];
300
- case 8:
301
- result = _b.sent();
302
- return [3 /*break*/, 10];
303
- case 9: throw new Error("Unsupported method: ".concat(method));
304
- case 10:
305
- res.status(200).json({ success: true, result: result });
306
- return [3 /*break*/, 12];
307
- case 11:
308
- err_1 = _b.sent();
309
- next(err_1);
310
- return [3 /*break*/, 12];
311
- case 12: return [2 /*return*/];
312
- }
313
- });
314
- });
315
- };
316
- CarbonSqlExecutor.prototype.buildBooleanJoinedConditions = function (set, andMode) {
317
- if (andMode === void 0) { andMode = true; }
318
- var booleanOperator = andMode ? 'AND' : 'OR';
319
- var sql = '';
320
- var OPERATORS = ['=', '!=', '<', '<=', '>', '>=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'IS', 'IS NOT'];
321
- var isAggregateArray = function (value) { return Array.isArray(value) && typeof value[0] === 'string' && OPERATORS.includes(value[0]); };
322
- var isNumericKeyed = function (obj) { return Array.isArray(obj) && Object.keys(obj).every(function (k) { return /^\d+$/.test(k); }); };
323
- // todo - we should be doing something with value no????
324
- var addCondition = function (column, op, _value) {
325
- var paramName = column.replace(/\W+/g, '_');
326
- return "(".concat(column, " ").concat(op, " :").concat(paramName, ")");
327
- };
328
- if (isNumericKeyed(set)) {
329
- switch (set.length) {
330
- case 2:
331
- sql += addCondition(set[0], '=', set[1]);
332
- break;
333
- case 3:
334
- if (!OPERATORS.includes(set[1])) {
335
- throw new Error("Invalid operator: ".concat(set[1]));
336
- }
337
- sql += addCondition(set[0], set[1], set[2]);
338
- break;
339
- default:
340
- throw new Error("Invalid array condition: ".concat(JSON.stringify(set)));
341
- }
342
- }
343
- else {
344
- var parts = [];
345
- for (var _i = 0, _a = Object.entries(set); _i < _a.length; _i++) {
346
- var _b = _a[_i], key = _b[0], value = _b[1];
347
- if (/^\d+$/.test(key)) {
348
- parts.push(this.buildBooleanJoinedConditions(value, !andMode));
349
- continue;
350
- }
351
- if (!Array.isArray(value) || isAggregateArray(value)) {
352
- parts.push(addCondition(key, '='));
353
- continue;
354
- }
355
- if (value.length === 2 && OPERATORS.includes(value[0])) {
356
- parts.push(addCondition(key, value[0], value[1]));
357
- }
358
- else if (value.length === 1 && isAggregateArray(value[0])) {
359
- parts.push(addCondition(key, '=', value[0]));
360
- }
361
- else {
362
- throw new Error("Invalid condition for ".concat(key, ": ").concat(JSON.stringify(value)));
363
- }
364
- }
365
- sql = parts.join(" ".concat(booleanOperator, " "));
366
- }
367
- return "(".concat(sql, ")");
368
- };
369
- CarbonSqlExecutor.prototype.buildAggregateField = function (field) {
370
- if (typeof field === 'string')
371
- return field;
372
- if (!Array.isArray(field))
373
- throw new Error('Invalid SELECT entry: must be string or array');
374
- var agg = field[0], args = field.slice(1);
375
- switch (agg) {
376
- case 'COUNT':
377
- return "COUNT(".concat(args[0] || '*', ")");
378
- case 'SUM':
379
- case 'AVG':
380
- case 'MIN':
381
- case 'MAX':
382
- return "".concat(agg, "(").concat(args[0], ")").concat(args[1] ? " AS ".concat(args[1]) : '');
383
- case 'DISTINCT':
384
- return "DISTINCT(".concat(args[0], ")").concat(args[1] ? " AS ".concat(args[1]) : '');
385
- case 'GROUP_CONCAT': {
386
- var col = args[0], alias = args[1], sortCol = args[2], sortType = args[3];
387
- var order = sortCol ? " ORDER BY ".concat(sortCol, " ").concat(sortType || 'ASC') : '';
388
- return "GROUP_CONCAT(DISTINCT ".concat(col).concat(order, " SEPARATOR ',')").concat(alias ? " AS ".concat(alias) : '');
389
- }
390
- case 'AS': {
391
- var col = args[0], alias = args[1];
392
- return "".concat(col, " AS ").concat(alias);
393
- }
394
- case 'CONVERT_TZ': {
395
- var ts = args[0], fromTz = args[1], toTz = args[2];
396
- return "CONVERT_TZ(".concat(ts, ", ").concat(fromTz, ", ").concat(toTz, ")");
397
- }
398
- case 'NOW':
399
- return 'NOW()';
400
- default:
401
- throw new Error("Unsupported aggregate: ".concat(agg));
402
- }
403
- };
404
- CarbonSqlExecutor.prototype.buildSelectQuery = function (table, primary, args, isSubSelect) {
405
- var _this = this;
406
- var _a, _b, _c, _d;
407
- if (isSubSelect === void 0) { isSubSelect = false; }
408
- var selectList = (_a = args === null || args === void 0 ? void 0 : args[this.C6.SELECT]) !== null && _a !== void 0 ? _a : ['*'];
409
- var selectFields = Array.isArray(selectList)
410
- ? selectList.map(function (f) { return _this.buildAggregateField(f); }).join(', ')
411
- : '*';
412
- var sql = "SELECT ".concat(selectFields, " FROM `").concat(table, "`");
413
- if (args === null || args === void 0 ? void 0 : args[this.C6.JOIN]) {
414
- var joins = args[this.C6.JOIN];
415
- for (var joinType in joins) {
416
- var joinKeyword = joinType.replace('_', ' ').toUpperCase();
417
- for (var joinTable in joins[joinType]) {
418
- var onClause = this.buildBooleanJoinedConditions(joins[joinType][joinTable]);
419
- sql += " ".concat(joinKeyword, " JOIN `").concat(joinTable, "` ON ").concat(onClause);
420
- }
421
- }
422
- }
423
- if (args === null || args === void 0 ? void 0 : args[this.C6.WHERE]) {
424
- sql += " WHERE ".concat(this.buildBooleanJoinedConditions(args[this.C6.WHERE]));
425
- }
426
- if (args === null || args === void 0 ? void 0 : args[this.C6.GROUP_BY]) {
427
- var groupByFields = Array.isArray(args[this.C6.GROUP_BY]) ? args[this.C6.GROUP_BY].join(', ') : args[this.C6.GROUP_BY];
428
- sql += " GROUP BY ".concat(groupByFields);
429
- }
430
- if (args === null || args === void 0 ? void 0 : args[this.C6.HAVING]) {
431
- sql += " HAVING ".concat(this.buildBooleanJoinedConditions(args[this.C6.HAVING]));
432
- }
433
- if (args === null || args === void 0 ? void 0 : args[this.C6.PAGINATION]) {
434
- var p = args[this.C6.PAGINATION];
435
- var limitClause = '';
436
- if (p[this.C6.ORDER]) {
437
- var orderArray = Object.entries(p[this.C6.ORDER]).map(function (_a) {
438
- var col = _a[0], dir = _a[1];
439
- if (!['ASC', 'DESC'].includes(String(dir).toUpperCase())) {
440
- throw new Error("Invalid order direction: ".concat(dir));
441
- }
442
- return "".concat(col, " ").concat(String(dir).toUpperCase());
443
- });
444
- sql += " ORDER BY ".concat(orderArray.join(', '));
445
- }
446
- else if (primary) {
447
- sql += " ORDER BY ".concat(primary, " DESC");
448
- }
449
- else {
450
- // todo this is wrong
451
- 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';
452
- sql += " ORDER BY ".concat(primaryKey, " DESC");
453
- }
454
- if (p[this.C6.LIMIT] != null) {
455
- var limit = parseInt(p[this.C6.LIMIT], 10);
456
- if (isNaN(limit) || limit < 0) {
457
- throw new Error("Invalid LIMIT: ".concat(p[this.C6.LIMIT]));
458
- }
459
- var page = parseInt((_d = p[this.C6.PAGE]) !== null && _d !== void 0 ? _d : 1, 10);
460
- if (isNaN(page) || page < 1) {
461
- throw new Error("PAGE must be >= 1 (got ".concat(p[this.C6.PAGE], ")"));
462
- }
463
- var offset = (page - 1) * limit;
464
- limitClause += " LIMIT ".concat(offset, ", ").concat(limit);
465
- }
466
- sql += limitClause;
467
- }
468
- else if (!isSubSelect && primary) {
469
- sql += " ORDER BY ".concat(primary, " ASC LIMIT 1");
470
- }
471
- else if (!isSubSelect && !primary) {
472
- sql += " ORDER BY id ASC LIMIT 100"; // fallback default limit
473
- }
474
- return sql;
475
- };
476
- CarbonSqlExecutor.prototype.select = function (table, primary, args) {
477
- return __awaiter(this, void 0, void 0, function () {
478
- var sql;
479
- var _this = this;
480
- return __generator(this, function (_a) {
481
- switch (_a.label) {
482
- case 0:
483
- sql = this.buildSelectQuery(table, primary, args);
484
- return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
485
- var rows;
486
- return __generator(this, function (_a) {
487
- switch (_a.label) {
488
- case 0:
489
- console.log(sql);
490
- return [4 /*yield*/, conn.query(sql)];
491
- case 1:
492
- rows = (_a.sent())[0];
493
- return [2 /*return*/, rows];
494
- }
495
- });
496
- }); })];
497
- case 1: return [2 /*return*/, _a.sent()];
498
- }
499
- });
500
- });
501
- };
502
- CarbonSqlExecutor.prototype.insert = function (table, data) {
503
- return __awaiter(this, void 0, void 0, function () {
504
- var keys, values, placeholders, sql;
505
- var _this = this;
506
- return __generator(this, function (_a) {
507
- switch (_a.label) {
508
- case 0:
509
- keys = Object.keys(data);
510
- values = keys.map(function (k) { return data[k]; });
511
- placeholders = keys.map(function () { return '?'; }).join(', ');
512
- sql = "INSERT INTO `".concat(table, "` (").concat(keys.join(', '), ") VALUES (").concat(placeholders, ")");
513
- return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
514
- var result;
515
- return __generator(this, function (_a) {
516
- switch (_a.label) {
517
- case 0: return [4 /*yield*/, conn.execute(sql, values)];
518
- case 1:
519
- result = (_a.sent())[0];
520
- return [2 /*return*/, result];
521
- }
522
- });
523
- }); })];
524
- case 1: return [2 /*return*/, _a.sent()];
525
- }
526
- });
527
- });
528
- };
529
- CarbonSqlExecutor.prototype.update = function (table, primary, data) {
530
- return __awaiter(this, void 0, void 0, function () {
531
- var keys, values, updates, sql;
532
- var _this = this;
533
- return __generator(this, function (_a) {
534
- switch (_a.label) {
535
- case 0:
536
- if (!primary) {
537
- throw new Error('Primary key is required for update');
538
- }
539
- keys = Object.keys(data);
540
- values = keys.map(function (k) { return data[k]; });
541
- updates = keys.map(function (k) { return "`".concat(k, "` = ?"); }).join(', ');
542
- sql = "UPDATE `".concat(table, "` SET ").concat(updates, " WHERE `").concat(primary, "` = ?");
543
- values.push(data[primary]);
544
- return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
545
- var result;
546
- return __generator(this, function (_a) {
547
- switch (_a.label) {
548
- case 0: return [4 /*yield*/, conn.execute(sql, values)];
549
- case 1:
550
- result = (_a.sent())[0];
551
- return [2 /*return*/, result];
552
- }
553
- });
554
- }); })];
555
- case 1: return [2 /*return*/, _a.sent()];
556
- }
557
- });
558
- });
559
- };
560
- CarbonSqlExecutor.prototype.delete = function (table, primary, args) {
561
- return __awaiter(this, void 0, void 0, function () {
562
- var sql;
563
- var _this = this;
564
- return __generator(this, function (_a) {
565
- switch (_a.label) {
566
- case 0:
567
- if (!primary || !(args === null || args === void 0 ? void 0 : args[primary])) {
568
- throw new Error('Primary key and value required for delete');
569
- }
570
- sql = "DELETE FROM `".concat(table, "` WHERE `").concat(primary, "` = ?");
571
- return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
572
- var result;
573
- return __generator(this, function (_a) {
574
- switch (_a.label) {
575
- case 0: return [4 /*yield*/, conn.execute(sql, [args[primary]])];
576
- case 1:
577
- result = (_a.sent())[0];
578
- return [2 /*return*/, result];
579
- }
580
- });
581
- }); })];
582
- case 1: return [2 /*return*/, _a.sent()];
583
- }
584
- });
585
- });
586
- };
587
- return CarbonSqlExecutor;
588
- }());
589
-
590
- var carbonSqlExecutor = /*#__PURE__*/Object.freeze({
591
- __proto__: null,
592
- CarbonSqlExecutor: CarbonSqlExecutor
593
- });
594
-
595
235
  function convertForRequestBody (restfulObject, tableName, C6, regexErrorHandler) {
596
236
  if (regexErrorHandler === void 0) { regexErrorHandler = alert; }
597
237
  var payload = {};
@@ -666,6 +306,221 @@ function convertForRequestBody (restfulObject, tableName, C6, regexErrorHandler)
666
306
  var _a;
667
307
  var isNode = typeof process !== 'undefined' && !!((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node);
668
308
 
309
+ /**
310
+ * Facade: routes API calls to SQL or HTTP executors based on runtime context.
311
+ */
312
+ function restRequest(config) {
313
+ var _this = this;
314
+ return function () {
315
+ var args_1 = [];
316
+ for (var _i = 0; _i < arguments.length; _i++) {
317
+ args_1[_i] = arguments[_i];
318
+ }
319
+ return __awaiter(_this, __spreadArray([], args_1, true), void 0, function (request) {
320
+ var SqlExecutor, executor, HttpExecutor, http;
321
+ if (request === void 0) { request = {}; }
322
+ return __generator(this, function (_a) {
323
+ switch (_a.label) {
324
+ case 0:
325
+ if (!(isNode && config.mysqlPool)) return [3 /*break*/, 2];
326
+ return [4 /*yield*/, Promise.resolve().then(function () { return SqlExecutor$1; })];
327
+ case 1:
328
+ SqlExecutor = (_a.sent()).SqlExecutor;
329
+ executor = new SqlExecutor(config, request);
330
+ return [2 /*return*/, executor.execute()];
331
+ case 2: return [4 /*yield*/, Promise.resolve().then(function () { return HttpExecutor$1; })];
332
+ case 3:
333
+ HttpExecutor = (_a.sent()).HttpExecutor;
334
+ http = new HttpExecutor(config, request);
335
+ return [2 /*return*/, http.execute()];
336
+ }
337
+ });
338
+ });
339
+ };
340
+ }
341
+
342
+ function timeout(shouldContinueAfterTimeout, cb, timeoutMs) {
343
+ if (timeoutMs === void 0) { timeoutMs = 3000; }
344
+ var timer = function () { return setTimeout(function () {
345
+ if (false === shouldContinueAfterTimeout()) {
346
+ return;
347
+ }
348
+ cb();
349
+ }, timeoutMs); };
350
+ var timerId = timer();
351
+ return function () {
352
+ clearTimeout(timerId);
353
+ };
354
+ }
355
+
356
+ function buildBooleanJoinedConditions(set, andMode) {
357
+ if (andMode === void 0) { andMode = true; }
358
+ var booleanOperator = andMode ? 'AND' : 'OR';
359
+ var sql = '';
360
+ var OPERATORS = ['=', '!=', '<', '<=', '>', '>=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'IS', 'IS NOT'];
361
+ var isAggregateArray = function (value) { return Array.isArray(value) && typeof value[0] === 'string' && OPERATORS.includes(value[0]); };
362
+ var isNumericKeyed = function (obj) { return Array.isArray(obj) && Object.keys(obj).every(function (k) { return /^\d+$/.test(k); }); };
363
+ // todo - we should be doing something with value no????
364
+ var addCondition = function (column, op, _value) {
365
+ var paramName = column.replace(/\W+/g, '_');
366
+ return "(".concat(column, " ").concat(op, " :").concat(paramName, ")");
367
+ };
368
+ if (isNumericKeyed(set)) {
369
+ switch (set.length) {
370
+ case 2:
371
+ sql += addCondition(set[0], '=', set[1]);
372
+ break;
373
+ case 3:
374
+ if (!OPERATORS.includes(set[1])) {
375
+ throw new Error("Invalid operator: ".concat(set[1]));
376
+ }
377
+ sql += addCondition(set[0], set[1], set[2]);
378
+ break;
379
+ default:
380
+ throw new Error("Invalid array condition: ".concat(JSON.stringify(set)));
381
+ }
382
+ }
383
+ else {
384
+ var parts = [];
385
+ for (var _i = 0, _a = Object.entries(set); _i < _a.length; _i++) {
386
+ var _b = _a[_i], key = _b[0], value = _b[1];
387
+ if (/^\d+$/.test(key)) {
388
+ parts.push(buildBooleanJoinedConditions(value, !andMode));
389
+ continue;
390
+ }
391
+ if (!Array.isArray(value) || isAggregateArray(value)) {
392
+ parts.push(addCondition(key, '='));
393
+ continue;
394
+ }
395
+ if (value.length === 2 && OPERATORS.includes(value[0])) {
396
+ parts.push(addCondition(key, value[0], value[1]));
397
+ }
398
+ else if (value.length === 1 && isAggregateArray(value[0])) {
399
+ parts.push(addCondition(key, '=', value[0]));
400
+ }
401
+ else {
402
+ throw new Error("Invalid condition for ".concat(key, ": ").concat(JSON.stringify(value)));
403
+ }
404
+ }
405
+ sql = parts.join(" ".concat(booleanOperator, " "));
406
+ }
407
+ return "(".concat(sql, ")");
408
+ }
409
+ function buildAggregateField(field) {
410
+ if (typeof field === 'string')
411
+ return field;
412
+ if (!Array.isArray(field))
413
+ throw new Error('Invalid SELECT entry: must be string or array');
414
+ var agg = field[0], args = field.slice(1);
415
+ switch (agg) {
416
+ case 'COUNT':
417
+ return "COUNT(".concat(args[0] || '*', ")");
418
+ case 'SUM':
419
+ case 'AVG':
420
+ case 'MIN':
421
+ case 'MAX':
422
+ return "".concat(agg, "(").concat(args[0], ")").concat(args[1] ? " AS ".concat(args[1]) : '');
423
+ case 'DISTINCT':
424
+ return "DISTINCT(".concat(args[0], ")").concat(args[1] ? " AS ".concat(args[1]) : '');
425
+ case 'GROUP_CONCAT': {
426
+ var col = args[0], alias = args[1], sortCol = args[2], sortType = args[3];
427
+ var order = sortCol ? " ORDER BY ".concat(sortCol, " ").concat(sortType || 'ASC') : '';
428
+ return "GROUP_CONCAT(DISTINCT ".concat(col).concat(order, " SEPARATOR ',')").concat(alias ? " AS ".concat(alias) : '');
429
+ }
430
+ case 'AS': {
431
+ var col = args[0], alias = args[1];
432
+ return "".concat(col, " AS ").concat(alias);
433
+ }
434
+ case 'CONVERT_TZ': {
435
+ var ts = args[0], fromTz = args[1], toTz = args[2];
436
+ return "CONVERT_TZ(".concat(ts, ", ").concat(fromTz, ", ").concat(toTz, ")");
437
+ }
438
+ case 'NOW':
439
+ return 'NOW()';
440
+ default:
441
+ throw new Error("Unsupported aggregate: ".concat(agg));
442
+ }
443
+ }
444
+ function buildSelectQuery(table, primary, args, isSubSelect) {
445
+ var _a, _b;
446
+ if (isSubSelect === void 0) { isSubSelect = false; }
447
+ var selectList = (_a = args === null || args === void 0 ? void 0 : args[C6Constants.SELECT]) !== null && _a !== void 0 ? _a : ['*'];
448
+ var selectFields = Array.isArray(selectList)
449
+ ? selectList.map(function (f) { return buildAggregateField(f); }).join(', ')
450
+ : '*';
451
+ var sql = "SELECT ".concat(selectFields, " FROM `").concat(table, "`");
452
+ if (args === null || args === void 0 ? void 0 : args[C6Constants.JOIN]) {
453
+ var joins = args[C6Constants.JOIN];
454
+ for (var joinType in joins) {
455
+ var joinKeyword = joinType.replace('_', ' ').toUpperCase();
456
+ for (var joinTable in joins[joinType]) {
457
+ var onClause = buildBooleanJoinedConditions(joins[joinType][joinTable]);
458
+ sql += " ".concat(joinKeyword, " JOIN `").concat(joinTable, "` ON ").concat(onClause);
459
+ }
460
+ }
461
+ }
462
+ if (args === null || args === void 0 ? void 0 : args[C6Constants.WHERE]) {
463
+ sql += " WHERE ".concat(buildBooleanJoinedConditions(args[C6Constants.WHERE]));
464
+ }
465
+ if (args === null || args === void 0 ? void 0 : args[C6Constants.GROUP_BY]) {
466
+ var groupByFields = Array.isArray(args[C6Constants.GROUP_BY]) ? args[C6Constants.GROUP_BY].join(', ') : args[C6Constants.GROUP_BY];
467
+ sql += " GROUP BY ".concat(groupByFields);
468
+ }
469
+ if (args === null || args === void 0 ? void 0 : args[C6Constants.HAVING]) {
470
+ sql += " HAVING ".concat(buildBooleanJoinedConditions(args[C6Constants.HAVING]));
471
+ }
472
+ if (args === null || args === void 0 ? void 0 : args[C6Constants.PAGINATION]) {
473
+ var p = args[C6Constants.PAGINATION];
474
+ var limitClause = '';
475
+ if (p[C6Constants.ORDER]) {
476
+ var orderArray = Object.entries(p[C6Constants.ORDER]).map(function (_a) {
477
+ var col = _a[0], dir = _a[1];
478
+ if (!['ASC', 'DESC'].includes(String(dir).toUpperCase())) {
479
+ throw new Error("Invalid order direction: ".concat(dir));
480
+ }
481
+ return "".concat(col, " ").concat(String(dir).toUpperCase());
482
+ });
483
+ sql += " ORDER BY ".concat(orderArray.join(', '));
484
+ }
485
+ else if (primary) {
486
+ sql += " ORDER BY ".concat(primary, " DESC");
487
+ } /*else {
488
+ // todo - this is wrong
489
+ const primaryKey = C6Constants.TABLES['users'].PRIMARY_SHORT?.[0] ?? 'user_id';
490
+ sql += ` ORDER BY ${primaryKey} DESC`;
491
+ }*/
492
+ if (p[C6Constants.LIMIT] != null) {
493
+ var limit = parseInt(p[C6Constants.LIMIT], 10);
494
+ if (isNaN(limit) || limit < 0) {
495
+ throw new Error("Invalid LIMIT: ".concat(p[C6Constants.LIMIT]));
496
+ }
497
+ var page = parseInt((_b = p[C6Constants.PAGE]) !== null && _b !== void 0 ? _b : 1, 10);
498
+ if (isNaN(page) || page < 1) {
499
+ throw new Error("PAGE must be >= 1 (got ".concat(p[C6Constants.PAGE], ")"));
500
+ }
501
+ var offset = (page - 1) * limit;
502
+ limitClause += " LIMIT ".concat(offset, ", ").concat(limit);
503
+ }
504
+ sql += limitClause;
505
+ }
506
+ else if (!isSubSelect && primary) {
507
+ sql += " ORDER BY ".concat(primary, " ASC LIMIT 1");
508
+ }
509
+ else if (!isSubSelect && !primary) {
510
+ sql += " ORDER BY id ASC LIMIT 100"; // fallback default limit
511
+ }
512
+ return sql;
513
+ }
514
+
515
+ var Executor = /** @class */ (function () {
516
+ function Executor(config, request) {
517
+ if (request === void 0) { request = {}; }
518
+ this.config = config;
519
+ this.request = request;
520
+ }
521
+ return Executor;
522
+ }());
523
+
669
524
  function getEnvVar(key, fallback) {
670
525
  if (fallback === void 0) { fallback = ''; }
671
526
  // Vite-style injection
@@ -690,6 +545,36 @@ var isTest = getEnvVar('JEST_WORKER_ID') || getEnvVar('NODE_ENV') === 'test'
690
545
  var envVerbose = getEnvVar('VERBOSE') || getEnvVar('REACT_APP_VERBOSE') || getEnvVar('VITE_VERBOSE') || '';
691
546
  var isVerbose = ['true', '1', 'yes', 'on'].includes(envVerbose.toLowerCase());
692
547
 
548
+ var eFetchDependencies;
549
+ (function (eFetchDependencies) {
550
+ eFetchDependencies[eFetchDependencies["NONE"] = 0] = "NONE";
551
+ eFetchDependencies[eFetchDependencies["REFERENCED"] = 1] = "REFERENCED";
552
+ eFetchDependencies[eFetchDependencies["CHILDREN"] = 1] = "CHILDREN";
553
+ eFetchDependencies[eFetchDependencies["REFERENCES"] = 2] = "REFERENCES";
554
+ eFetchDependencies[eFetchDependencies["PARENTS"] = 2] = "PARENTS";
555
+ eFetchDependencies[eFetchDependencies["ALL"] = 3] = "ALL";
556
+ eFetchDependencies[eFetchDependencies["C6ENTITY"] = 4] = "C6ENTITY";
557
+ eFetchDependencies[eFetchDependencies["RECURSIVE"] = 8] = "RECURSIVE";
558
+ })(eFetchDependencies || (eFetchDependencies = {}));
559
+
560
+ /**
561
+ * the first argument ....
562
+ *
563
+ * Our api returns a zero argument function iff the method is get and the previous request reached the predefined limit.
564
+ * This function can be aliased as GetNextPageOfResults(). If the end is reached undefined will be returned.
565
+ *
566
+ *
567
+ * For POST, PUT, and DELETE requests one can expect the primary key of the new or modified index, or a boolean success
568
+ * indication if no primary key exists.
569
+ **/
570
+ var POST = 'POST';
571
+ var PUT = 'PUT';
572
+ var GET = 'GET';
573
+ var DELETE = 'DELETE';
574
+ function isPromise(x) {
575
+ return Object(x).constructor === Promise;
576
+ }
577
+
693
578
  var toastOptions = {
694
579
  position: "bottom-left",
695
580
  autoClose: 10000,
@@ -730,6 +615,12 @@ function TestRestfulResponse(response, success, error) {
730
615
  }
731
616
  return false;
732
617
  }
618
+ function removePrefixIfExists(tableName, prefix) {
619
+ if (tableName.startsWith(prefix.toLowerCase())) {
620
+ return tableName.slice(prefix.length);
621
+ }
622
+ return tableName;
623
+ }
733
624
  function removeInvalidKeys(request, c6Tables) {
734
625
  var intersection = {};
735
626
  var restfulObjectKeys = [];
@@ -747,61 +638,11 @@ function removeInvalidKeys(request, c6Tables) {
747
638
  isTest || console.log('intersection', intersection);
748
639
  return intersection;
749
640
  }
750
- var eFetchDependencies;
751
- (function (eFetchDependencies) {
752
- eFetchDependencies[eFetchDependencies["NONE"] = 0] = "NONE";
753
- eFetchDependencies[eFetchDependencies["REFERENCED"] = 1] = "REFERENCED";
754
- eFetchDependencies[eFetchDependencies["CHILDREN"] = 1] = "CHILDREN";
755
- eFetchDependencies[eFetchDependencies["REFERENCES"] = 2] = "REFERENCES";
756
- eFetchDependencies[eFetchDependencies["PARENTS"] = 2] = "PARENTS";
757
- eFetchDependencies[eFetchDependencies["ALL"] = 3] = "ALL";
758
- eFetchDependencies[eFetchDependencies["C6ENTITY"] = 4] = "C6ENTITY";
759
- eFetchDependencies[eFetchDependencies["RECURSIVE"] = 8] = "RECURSIVE";
760
- })(eFetchDependencies || (eFetchDependencies = {}));
641
+
761
642
  // do not remove entries from this array. It is used to track the progress of API requests.
762
643
  // position in array is important. Do not sort. To not add to begging.
763
644
  var apiRequestCache = [];
764
645
  var userCustomClearCache = [];
765
- function checkAllRequestsComplete() {
766
- var stillRunning = apiRequestCache.filter(function (cache) { return undefined === cache.response; });
767
- if (stillRunning.length !== 0) {
768
- if (document === null || document === undefined) {
769
- throw new Error('document is undefined while waiting for API requests to complete (' + JSON.stringify(apiRequestCache) + ')');
770
- }
771
- // when requests return emtpy sets in full renders, it may not be possible to track their progress.
772
- console.warn('stillRunning...', stillRunning);
773
- return stillRunning.map(function (cache) { return cache.requestArgumentsSerialized; });
774
- }
775
- return true;
776
- }
777
- function checkCache(cacheResult, requestMethod, tableName, request) {
778
- var _a, _b, _c;
779
- if (undefined === (cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.response)) {
780
- console.groupCollapsed('%c API: The request on (' + tableName + ') is in cache and the response is undefined. The request has not finished. Returning the request Promise!', 'color: #0c0');
781
- console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
782
- console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', request);
783
- console.groupEnd();
784
- return cacheResult.request;
785
- }
786
- if (true === (cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.final)) {
787
- if (false === isTest || true === isVerbose) {
788
- console.groupCollapsed('%c API: Rest api cache (' + requestMethod + ' ' + tableName + ') has reached the final result. Returning undefined!', 'color: #cc0');
789
- console.log('%c ' + requestMethod + ' ' + tableName, 'color: #cc0');
790
- console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #cc0', request);
791
- console.log('%c Response Data:', 'color: #cc0', ((_b = (_a = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.rest) || ((_c = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.response) === null || _c === void 0 ? void 0 : _c.data) || (cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.response));
792
- console.groupEnd();
793
- }
794
- return undefined;
795
- }
796
- return false;
797
- }
798
- function sortAndSerializeQueryObject(tables, query) {
799
- var orderedQuery = Object.keys(query).sort().reduce(function (obj, key) {
800
- obj[key] = query[key];
801
- return obj;
802
- }, {});
803
- return tables + ' ' + JSON.stringify(orderedQuery);
804
- }
805
646
  function clearCache(props) {
806
647
  if (false === (props === null || props === void 0 ? void 0 : props.ignoreWarning)) {
807
648
  console.warn('The rest api clearCache should only be used with extreme care! Avoid using this in favor of using `cacheResults : boolean`.');
@@ -809,72 +650,104 @@ function clearCache(props) {
809
650
  userCustomClearCache.map(function (f) { return 'function' === typeof f && f(); });
810
651
  userCustomClearCache = apiRequestCache = [];
811
652
  }
812
- function removePrefixIfExists(tableName, prefix) {
813
- if (tableName.startsWith(prefix.toLowerCase())) {
814
- return tableName.slice(prefix.length);
815
- }
816
- return tableName;
817
- }
818
- /**
819
- * the first argument ....
820
- *
821
- * Our api returns a zero argument function iff the method is get and the previous request reached the predefined limit.
822
- * This function can be aliased as GetNextPageOfResults(). If the end is reached undefined will be returned.
823
- *
824
- *
825
- * For POST, PUT, and DELETE requests one can expect the primary key of the new or modified index, or a boolean success
826
- * indication if no primary key exists.
827
- **/
828
- var POST = 'POST';
829
- var PUT = 'PUT';
830
- var GET = 'GET';
831
- var DELETE = 'DELETE';
832
- function isPromise(x) {
833
- return Object(x).constructor === Promise;
653
+ function checkCache(cacheResult, requestMethod, tableName, request) {
654
+ var _a, _b, _c;
655
+ if (undefined === (cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.response)) {
656
+ console.groupCollapsed('%c API: The request on (' + tableName + ') is in cache and the response is undefined. The request has not finished. Returning the request Promise!', 'color: #0c0');
657
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
658
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', request);
659
+ console.groupEnd();
660
+ return cacheResult.request;
661
+ }
662
+ if (true === (cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.final)) {
663
+ if (false === isTest || true === isVerbose) {
664
+ console.groupCollapsed('%c API: Rest api cache (' + requestMethod + ' ' + tableName + ') has reached the final result. Returning undefined!', 'color: #cc0');
665
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #cc0');
666
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #cc0', request);
667
+ console.log('%c Response Data:', 'color: #cc0', ((_b = (_a = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.rest) || ((_c = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.response) === null || _c === void 0 ? void 0 : _c.data) || (cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.response));
668
+ console.groupEnd();
669
+ }
670
+ return undefined;
671
+ }
672
+ return false;
834
673
  }
835
- function extendedTypeHints() {
836
- return function (argv) { return restRequest(argv); };
674
+
675
+ function sortAndSerializeQueryObject(tables, query) {
676
+ var orderedQuery = Object.keys(query).sort().reduce(function (obj, key) {
677
+ obj[key] = query[key];
678
+ return obj;
679
+ }, {});
680
+ return tables + ' ' + JSON.stringify(orderedQuery);
837
681
  }
838
- function restRequest(_a) {
839
- var _this = this;
840
- 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;
841
- var fullTableList = Array.isArray(tableName) ? tableName : [tableName];
842
- var operatingTableFullName = fullTableList[0];
843
- var operatingTable = removePrefixIfExists(operatingTableFullName, C6.PREFIX);
844
- var tables = fullTableList.join(',');
845
- switch (requestMethod) {
846
- case GET:
847
- case POST:
848
- case PUT:
849
- case DELETE:
850
- break;
851
- default:
852
- throw Error('Bad request method passed to getApi');
853
- }
854
- if (null !== clearCache || undefined !== clearCache) {
855
- userCustomClearCache[tables + requestMethod] = clearCache;
682
+
683
+ var HttpExecutor = /** @class */ (function (_super) {
684
+ __extends(HttpExecutor, _super);
685
+ function HttpExecutor() {
686
+ return _super !== null && _super.apply(this, arguments) || this;
856
687
  }
857
- return function () {
858
- var args_1 = [];
859
- for (var _i = 0; _i < arguments.length; _i++) {
860
- args_1[_i] = arguments[_i];
861
- }
862
- return __awaiter(_this, __spreadArray([], args_1, true), void 0, function (request) {
863
- // this could return itself with a new page number, or undefined if the end is reached
864
- function apiRequest() {
865
- return __awaiter(this, void 0, void 0, function () {
866
- var querySerialized, cacheResult, cachingConfirmed, cacheCheck, cacheCheck, addBackPK, apiResponse, returnGetNextPageFunction, restRequestUri, needsConditionOrPrimaryCheck, TABLES, primaryKey, CarbonSqlExecutor, engine, removedPkValue_1, axiosActiveRequest;
867
- var _this = this;
868
- var _a, _b, _c, _d, _e, _f, _g;
869
- return __generator(this, function (_h) {
870
- switch (_h.label) {
871
- case 0:
872
- (_a = request.cacheResults) !== null && _a !== void 0 ? _a : (request.cacheResults = C6.GET === requestMethod);
688
+ HttpExecutor.prototype.execute = function () {
689
+ return __awaiter(this, void 0, void 0, function () {
690
+ var _a, C6, axios, restURL, withCredentials, restModel, requestMethod, queryCallback, responseCallback, skipPrimaryCheck, clearCache, tableName, fullTableList, operatingTableFullName, operatingTable, tables, query, apiRequest;
691
+ var _this = this;
692
+ return __generator(this, function (_b) {
693
+ switch (_b.label) {
694
+ case 0:
695
+ _a = this.config, C6 = _a.C6, axios = _a.axios, restURL = _a.restURL, withCredentials = _a.withCredentials, restModel = _a.restModel, requestMethod = _a.requestMethod, queryCallback = _a.queryCallback, responseCallback = _a.responseCallback, skipPrimaryCheck = _a.skipPrimaryCheck, clearCache = _a.clearCache;
696
+ tableName = restModel.TABLE_NAME;
697
+ fullTableList = Array.isArray(tableName) ? tableName : [tableName];
698
+ operatingTableFullName = fullTableList[0];
699
+ operatingTable = removePrefixIfExists(operatingTableFullName, C6.PREFIX);
700
+ tables = fullTableList.join(',');
701
+ switch (requestMethod) {
702
+ case GET:
703
+ case POST:
704
+ case PUT:
705
+ case DELETE:
706
+ break;
707
+ default:
708
+ throw Error('Bad request method passed to getApi');
709
+ }
710
+ if (null !== clearCache || undefined !== clearCache) {
711
+ userCustomClearCache[tables + requestMethod] = clearCache;
712
+ }
713
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request for (' + tableName + ')', 'color: #0c0');
714
+ console.log('request', this.request);
715
+ console.groupEnd();
716
+ if ('function' === typeof queryCallback) {
717
+ query = queryCallback(this.request); // obj or obj[]
718
+ }
719
+ else {
720
+ query = queryCallback;
721
+ }
722
+ if (undefined === query || null === query) {
723
+ if (this.request.debug && isDevelopment) {
724
+ toast.warning("DEV: queryCallback returned undefined, signaling in Custom Cache. (returning null)", toastOptionsDevs);
725
+ }
726
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + tableName + ') undefined, returning null (will not fire ajax)!', 'color: #c00');
727
+ 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');
728
+ console.trace();
729
+ console.groupEnd();
730
+ return [2 /*return*/, null];
731
+ }
732
+ if (C6.GET === requestMethod) {
733
+ if (undefined === query[C6.PAGINATION]) {
734
+ query[C6.PAGINATION] = {};
735
+ }
736
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
737
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
738
+ }
739
+ apiRequest = function () { return __awaiter(_this, void 0, void 0, function () {
740
+ 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;
741
+ var _e;
742
+ var _this = this;
743
+ var _f, _g, _h, _j, _k, _l;
744
+ return __generator(this, function (_m) {
745
+ _a = this.request, debug = _a.debug, _b = _a.cacheResults, cacheResults = _b === void 0 ? (C6.GET === requestMethod) : _b, dataInsertMultipleRows = _a.dataInsertMultipleRows, success = _a.success, _c = _a.fetchDependencies, fetchDependencies = _c === void 0 ? eFetchDependencies.NONE : _c, _d = _a.error, error = _d === void 0 ? "An unexpected API error occurred!" : _d;
873
746
  if (C6.GET === requestMethod
874
- && undefined !== ((_b = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _b === void 0 ? void 0 : _b[C6.PAGE])
747
+ && undefined !== ((_f = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _f === void 0 ? void 0 : _f[C6.PAGE])
875
748
  && 1 !== query[C6.PAGINATION][C6.PAGE]) {
876
749
  console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
877
- console.log('Request Data (note you may see the success and/or error prompt):', request);
750
+ console.log('Request Data (note you may see the success and/or error prompt):', this.request);
878
751
  console.trace();
879
752
  console.groupEnd();
880
753
  }
@@ -892,11 +765,11 @@ function restRequest(_a) {
892
765
  query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
893
766
  query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
894
767
  // this will evaluate true most the time
895
- if (true === request.cacheResults) {
768
+ if (true === cacheResults) {
896
769
  // just find the next, non-fetched, page and return a function to request it
897
770
  if (undefined !== cacheResult) {
898
771
  do {
899
- cacheCheck = checkCache(cacheResult, requestMethod, tableName, request);
772
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
900
773
  if (false !== cacheCheck) {
901
774
  return [2 /*return*/, cacheCheck];
902
775
  }
@@ -906,7 +779,7 @@ function restRequest(_a) {
906
779
  querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
907
780
  cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
908
781
  } while (undefined !== cacheResult);
909
- if (request.debug && isDevelopment) {
782
+ if (debug && isDevelopment) {
910
783
  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);
911
784
  }
912
785
  // @ts-ignore - this is an incorrect warning on TS, it's well typed
@@ -915,17 +788,17 @@ function restRequest(_a) {
915
788
  cachingConfirmed = true;
916
789
  }
917
790
  else {
918
- if (request.debug && isDevelopment) {
791
+ if (debug && isDevelopment) {
919
792
  toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
920
793
  }
921
794
  }
922
- if (request.debug && isDevelopment) {
795
+ if (debug && isDevelopment) {
923
796
  toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
924
797
  }
925
798
  }
926
- else if (request.cacheResults) { // if we are not getting, we are updating, deleting, or inserting
799
+ else if (cacheResults) { // if we are not getting, we are updating, deleting, or inserting
927
800
  if (cacheResult) {
928
- cacheCheck = checkCache(cacheResult, requestMethod, tableName, request);
801
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
929
802
  if (false !== cacheCheck) {
930
803
  return [2 /*return*/, cacheCheck];
931
804
  }
@@ -938,7 +811,7 @@ function restRequest(_a) {
938
811
  needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
939
812
  && false === skipPrimaryCheck;
940
813
  TABLES = C6.TABLES;
941
- 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();
814
+ 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();
942
815
  if (needsConditionOrPrimaryCheck) {
943
816
  if (undefined === primaryKey) {
944
817
  if (null === query
@@ -948,17 +821,17 @@ function restRequest(_a) {
948
821
  || query[C6.WHERE].length === 0)
949
822
  || (Object.keys(query === null || query === void 0 ? void 0 : query[C6.WHERE]).length === 0)) {
950
823
  console.error(query);
951
- 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 + ').');
824
+ 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 + ').');
952
825
  }
953
826
  }
954
827
  else {
955
828
  if (undefined === query
956
829
  || null === query
957
830
  || false === primaryKey in query) {
958
- if (true === request.debug && isDevelopment) {
831
+ if (true === debug && isDevelopment) {
959
832
  toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
960
833
  }
961
- throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
834
+ throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(this.request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
962
835
  }
963
836
  if (undefined === (query === null || query === void 0 ? void 0 : query[primaryKey])
964
837
  || null === (query === null || query === void 0 ? void 0 : query[primaryKey])) {
@@ -967,55 +840,6 @@ function restRequest(_a) {
967
840
  }
968
841
  }
969
842
  }
970
- if (!(isNode && mysqlPool)) return [3 /*break*/, 2];
971
- return [4 /*yield*/, Promise.resolve().then(function () { return carbonSqlExecutor; })];
972
- case 1:
973
- CarbonSqlExecutor = (_h.sent()).CarbonSqlExecutor;
974
- engine = new CarbonSqlExecutor(mysqlPool, C6);
975
- switch (requestMethod) {
976
- case GET:
977
- return [2 /*return*/, engine
978
- .select(tableName, undefined, request)
979
- .then(function (rows) {
980
- // mirror the front‐end shape
981
- var serverResponse = {
982
- rest: rows,
983
- session: undefined,
984
- sql: true,
985
- };
986
- return serverResponse;
987
- })];
988
- case POST:
989
- return [2 /*return*/, engine
990
- .insert(tableName, request)
991
- .then(function (created) { return ({
992
- rest: created,
993
- }); })];
994
- case PUT:
995
- return [2 /*return*/, engine
996
- .update(tableName, undefined, request)
997
- .then(function (updatedResult) {
998
- var _a;
999
- return ({
1000
- rest: updatedResult,
1001
- rowCount: (_a = updatedResult.affectedRows) !== null && _a !== void 0 ? _a : 0,
1002
- });
1003
- })];
1004
- case DELETE:
1005
- return [2 /*return*/, engine
1006
- .delete(tableName, undefined, request)
1007
- .then(function (deletedResult) {
1008
- var _a;
1009
- return ({
1010
- rest: deletedResult,
1011
- rowCount: (_a = deletedResult.affectedRows) !== null && _a !== void 0 ? _a : 0,
1012
- deleted: true,
1013
- });
1014
- })];
1015
- default:
1016
- throw new Error("Unsupported method: ".concat(requestMethod));
1017
- }
1018
- case 2:
1019
843
  // A part of me exists that wants to remove this, but it's a good feature
1020
844
  // this allows developers the ability to cache requests based on primary key
1021
845
  // for tables like `photos` this can be a huge performance boost
@@ -1037,12 +861,12 @@ function restRequest(_a) {
1037
861
  }
1038
862
  try {
1039
863
  console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
1040
- console.log(request);
864
+ console.log(this.request);
1041
865
  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');
1042
866
  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');
1043
867
  console.trace();
1044
868
  console.groupEnd();
1045
- axiosActiveRequest = axios[requestMethod.toLowerCase()].apply(axios, __spreadArray([restRequestUri], ((function () {
869
+ axiosActiveRequest = (_e = axios)[requestMethod.toLowerCase()].apply(_e, __spreadArray([restRequestUri], ((function () {
1046
870
  // @link - https://axios-http.com/docs/instance
1047
871
  // How configuration vs data is passed is variable, use documentation above for reference
1048
872
  if (requestMethod === GET) {
@@ -1052,9 +876,9 @@ function restRequest(_a) {
1052
876
  }];
1053
877
  }
1054
878
  else if (requestMethod === POST) {
1055
- if (undefined !== (request === null || request === void 0 ? void 0 : request.dataInsertMultipleRows)) {
879
+ if (undefined !== dataInsertMultipleRows) {
1056
880
  return [
1057
- request.dataInsertMultipleRows.map(function (data) {
881
+ dataInsertMultipleRows.map(function (data) {
1058
882
  return convertForRequestBody(data, fullTableList, C6, function (message) { return toast.error(message, toastOptions); });
1059
883
  }),
1060
884
  {
@@ -1100,11 +924,11 @@ function restRequest(_a) {
1100
924
  // returning the promise with this then is important for tests. todo - we could make that optional.
1101
925
  // https://rapidapi.com/guides/axios-async-await
1102
926
  return [2 /*return*/, axiosActiveRequest.then(function (response) { return __awaiter(_this, void 0, void 0, function () {
1103
- var cacheIndex, responseData_1, fetchDependencies, dependencies_1, fetchReferences_1, apiRequestPromises, _loop_1, _a, _b, _c, _i, tableToFetch;
927
+ var cacheIndex, responseData_1, dependencies_1, fetchReferences_1, apiRequestPromises, _loop_1, _a, _b, _c, _i, tableToFetch;
1104
928
  var _this = this;
1105
- var _d, _e, _f, _g, _h, _j, _k, _l, _m;
1106
- return __generator(this, function (_o) {
1107
- switch (_o.label) {
929
+ var _d, _e, _f, _g, _h, _j, _k;
930
+ return __generator(this, function (_l) {
931
+ switch (_l.label) {
1108
932
  case 0:
1109
933
  if (typeof response.data === 'string') {
1110
934
  if (isTest) {
@@ -1119,40 +943,38 @@ function restRequest(_a) {
1119
943
  // only cache get method requests
1120
944
  apiRequestCache[cacheIndex].response = response;
1121
945
  }
1122
- 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!");
946
+ apiResponse = TestRestfulResponse(response, success, error);
1123
947
  if (false === apiResponse) {
1124
- if (request.debug && isDevelopment) {
948
+ if (debug && isDevelopment) {
1125
949
  toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
1126
950
  }
1127
951
  return [2 /*return*/, response];
1128
952
  }
1129
953
  // stateful operations are done in the response callback - its leverages rest generated functions
1130
954
  if (responseCallback) {
1131
- responseCallback(response, request, apiResponse);
955
+ responseCallback(response, this.request, apiResponse);
1132
956
  }
1133
957
  if (!(C6.GET === requestMethod)) return [3 /*break*/, 6];
1134
958
  responseData_1 = response.data;
1135
- returnGetNextPageFunction = 1 !== ((_e = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _e === void 0 ? void 0 : _e[C6.LIMIT]) &&
1136
- ((_f = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _f === void 0 ? void 0 : _f[C6.LIMIT]) === responseData_1.rest.length;
959
+ returnGetNextPageFunction = 1 !== ((_d = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _d === void 0 ? void 0 : _d[C6.LIMIT]) &&
960
+ ((_e = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _e === void 0 ? void 0 : _e[C6.LIMIT]) === responseData_1.rest.length;
1137
961
  if (false === isTest || true === isVerbose) {
1138
- 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');
962
+ 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');
1139
963
  console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
1140
- console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', request);
964
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', this.request);
1141
965
  console.log('%c Response Data:', 'color: #0c0', responseData_1.rest);
1142
- 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);
966
+ 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);
1143
967
  console.trace();
1144
968
  console.groupEnd();
1145
969
  }
1146
970
  if (false === returnGetNextPageFunction
1147
- && true === request.debug
971
+ && true === debug
1148
972
  && isDevelopment) {
1149
- 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
+ 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);
1150
974
  }
1151
- (_m = request.fetchDependencies) !== null && _m !== void 0 ? _m : (request.fetchDependencies = eFetchDependencies.NONE);
1152
- if (!(request.fetchDependencies
1153
- && 'number' === typeof request.fetchDependencies
975
+ if (!(fetchDependencies
976
+ && 'number' === typeof fetchDependencies
1154
977
  && responseData_1.rest.length > 0)) return [3 /*break*/, 6];
1155
- fetchDependencies = request.fetchDependencies;
1156
978
  console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
1157
979
  + (fetchDependencies & eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
1158
980
  + (fetchDependencies & eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
@@ -1223,9 +1045,9 @@ function restRequest(_a) {
1223
1045
  console.log('fetchReferences', fetchReferences_1);
1224
1046
  _loop_1 = function (tableToFetch) {
1225
1047
  var referencesTables, shouldContinue, fetchTable, RestApi, nextFetchDependencies;
1226
- var _p;
1227
- return __generator(this, function (_q) {
1228
- switch (_q.label) {
1048
+ var _m;
1049
+ return __generator(this, function (_o) {
1050
+ switch (_o.label) {
1229
1051
  case 0:
1230
1052
  if (fetchDependencies & eFetchDependencies.C6ENTITY
1231
1053
  && 'string' === typeof tableName
@@ -1245,7 +1067,7 @@ function restRequest(_a) {
1245
1067
  }
1246
1068
  return [4 /*yield*/, C6.IMPORT(tableToFetch)];
1247
1069
  case 1:
1248
- fetchTable = _q.sent();
1070
+ fetchTable = _o.sent();
1249
1071
  RestApi = fetchTable.default;
1250
1072
  console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff');
1251
1073
  nextFetchDependencies = eFetchDependencies.NONE;
@@ -1268,8 +1090,8 @@ function restRequest(_a) {
1268
1090
  // it not certain that they are using carbons' entities either
1269
1091
  // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
1270
1092
  // todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
1271
- apiRequestPromises.push(RestApi.Get((_p = {},
1272
- _p[C6.WHERE] = {
1093
+ apiRequestPromises.push(RestApi.Get((_m = {},
1094
+ _m[C6.WHERE] = {
1273
1095
  0: Object.keys(fetchReferences_1[tableToFetch]).reduce(function (sum, column) {
1274
1096
  fetchReferences_1[tableToFetch][column] = fetchReferences_1[tableToFetch][column].flat(Infinity);
1275
1097
  if (0 === fetchReferences_1[tableToFetch][column].length) {
@@ -1284,8 +1106,8 @@ function restRequest(_a) {
1284
1106
  return sum;
1285
1107
  }, {})
1286
1108
  },
1287
- _p.fetchDependencies = nextFetchDependencies,
1288
- _p)));
1109
+ _m.fetchDependencies = nextFetchDependencies,
1110
+ _m)));
1289
1111
  return [2 /*return*/];
1290
1112
  }
1291
1113
  });
@@ -1295,7 +1117,7 @@ function restRequest(_a) {
1295
1117
  for (_c in _a)
1296
1118
  _b.push(_c);
1297
1119
  _i = 0;
1298
- _o.label = 1;
1120
+ _l.label = 1;
1299
1121
  case 1:
1300
1122
  if (!(_i < _b.length)) return [3 /*break*/, 4];
1301
1123
  _c = _b[_i];
@@ -1303,8 +1125,8 @@ function restRequest(_a) {
1303
1125
  tableToFetch = _c;
1304
1126
  return [5 /*yield**/, _loop_1(tableToFetch)];
1305
1127
  case 2:
1306
- _o.sent();
1307
- _o.label = 3;
1128
+ _l.sent();
1129
+ _l.label = 3;
1308
1130
  case 3:
1309
1131
  _i++;
1310
1132
  return [3 /*break*/, 1];
@@ -1312,16 +1134,17 @@ function restRequest(_a) {
1312
1134
  console.groupEnd();
1313
1135
  return [4 /*yield*/, Promise.all(apiRequestPromises)];
1314
1136
  case 5:
1315
- _o.sent();
1137
+ _l.sent();
1316
1138
  apiRequestPromises.map(function (promise) { return __awaiter(_this, void 0, void 0, function () {
1317
1139
  var _a, _b;
1318
1140
  return __generator(this, function (_c) {
1319
1141
  switch (_c.label) {
1320
1142
  case 0:
1321
- if (!Array.isArray(request.fetchDependencies)) {
1322
- request.fetchDependencies = [];
1143
+ if (!Array.isArray(this.request.fetchDependencies)) {
1144
+ // to reassign value we must ref the root
1145
+ this.request.fetchDependencies = [];
1323
1146
  }
1324
- _b = (_a = request.fetchDependencies).push;
1147
+ _b = (_a = this.request.fetchDependencies).push;
1325
1148
  return [4 /*yield*/, promise];
1326
1149
  case 1:
1327
1150
  _b.apply(_a, [_c.sent()]);
@@ -1329,9 +1152,9 @@ function restRequest(_a) {
1329
1152
  }
1330
1153
  });
1331
1154
  }); });
1332
- _o.label = 6;
1155
+ _l.label = 6;
1333
1156
  case 6:
1334
- if (request.debug && isDevelopment) {
1157
+ if (debug && isDevelopment) {
1335
1158
  toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1336
1159
  }
1337
1160
  return [2 /*return*/, response];
@@ -1339,75 +1162,289 @@ function restRequest(_a) {
1339
1162
  });
1340
1163
  }); })];
1341
1164
  }
1342
- catch (error) {
1165
+ catch (throwableError) {
1343
1166
  if (isTest) {
1344
- throw new Error(JSON.stringify(error));
1167
+ throw new Error(JSON.stringify(throwableError));
1345
1168
  }
1346
1169
  console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
1347
1170
  console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
1348
- console.warn(error);
1171
+ console.warn(throwableError);
1349
1172
  console.trace();
1350
1173
  console.groupEnd();
1351
- 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!");
1174
+ TestRestfulResponse(throwableError, success, error);
1352
1175
  return [2 /*return*/, null];
1353
1176
  }
1354
1177
  return [2 /*return*/];
1355
- }
1356
- });
1357
- });
1358
- }
1359
- var query;
1360
- if (request === void 0) { request = {}; }
1178
+ });
1179
+ }); };
1180
+ return [4 /*yield*/, apiRequest()];
1181
+ case 1: return [2 /*return*/, _b.sent()];
1182
+ }
1183
+ });
1184
+ });
1185
+ };
1186
+ return HttpExecutor;
1187
+ }(Executor));
1188
+
1189
+ var HttpExecutor$1 = /*#__PURE__*/Object.freeze({
1190
+ __proto__: null,
1191
+ HttpExecutor: HttpExecutor
1192
+ });
1193
+
1194
+ var SqlExecutor = /** @class */ (function (_super) {
1195
+ __extends(SqlExecutor, _super);
1196
+ function SqlExecutor() {
1197
+ return _super !== null && _super.apply(this, arguments) || this;
1198
+ }
1199
+ SqlExecutor.prototype.execute = function () {
1200
+ switch (this.config.requestMethod) {
1201
+ case 'GET':
1202
+ return this.select(this.config.restModel.TABLE_NAME, undefined, this.request).then(function (rows) { return ({ rest: rows }); });
1203
+ case 'POST':
1204
+ return this.insert(this.config.restModel.TABLE_NAME, this.request);
1205
+ case 'PUT':
1206
+ return this.update(this.config.restModel.TABLE_NAME, undefined, this.request);
1207
+ case 'DELETE':
1208
+ return this.delete(this.config.restModel.TABLE_NAME, undefined, this.request);
1209
+ }
1210
+ };
1211
+ SqlExecutor.prototype.withConnection = function (cb) {
1212
+ return __awaiter(this, void 0, void 0, function () {
1213
+ var conn;
1214
+ return __generator(this, function (_a) {
1215
+ switch (_a.label) {
1216
+ case 0: return [4 /*yield*/, this.config.mysqlPool.getConnection()];
1217
+ case 1:
1218
+ conn = _a.sent();
1219
+ _a.label = 2;
1220
+ case 2:
1221
+ _a.trys.push([2, , 4, 5]);
1222
+ return [4 /*yield*/, cb(conn)];
1223
+ case 3: return [2 /*return*/, _a.sent()];
1224
+ case 4:
1225
+ conn.release();
1226
+ return [7 /*endfinally*/];
1227
+ case 5: return [2 /*return*/];
1228
+ }
1229
+ });
1230
+ });
1231
+ };
1232
+ SqlExecutor.prototype.select = function (table, primary, args) {
1233
+ return __awaiter(this, void 0, void 0, function () {
1234
+ var sql;
1235
+ var _this = this;
1361
1236
  return __generator(this, function (_a) {
1362
1237
  switch (_a.label) {
1363
1238
  case 0:
1364
- console.groupCollapsed('%c API: (' + requestMethod + ') Request for (' + operatingTable + ')', 'color: #0c0');
1365
- console.log('request', request);
1366
- console.groupEnd();
1367
- if ('function' === typeof queryCallback) {
1368
- query = queryCallback(request); // obj or obj[]
1369
- }
1370
- else {
1371
- query = queryCallback;
1372
- }
1373
- if (undefined === query || null === query) {
1374
- if (request.debug && isDevelopment) {
1375
- toast.warning("DEV: queryCallback returned undefined, signaling in Custom Cache. (returning null)", toastOptionsDevs);
1376
- }
1377
- console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') undefined, returning null (will not fire ajax)!', 'color: #c00');
1378
- 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');
1379
- console.trace();
1380
- console.groupEnd();
1381
- return [2 /*return*/, null];
1239
+ sql = buildSelectQuery(table, primary, args);
1240
+ return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
1241
+ var rows;
1242
+ return __generator(this, function (_a) {
1243
+ switch (_a.label) {
1244
+ case 0:
1245
+ console.log(sql);
1246
+ return [4 /*yield*/, conn.query(sql)];
1247
+ case 1:
1248
+ rows = (_a.sent())[0];
1249
+ return [2 /*return*/, rows];
1250
+ }
1251
+ });
1252
+ }); })];
1253
+ case 1: return [2 /*return*/, _a.sent()];
1254
+ }
1255
+ });
1256
+ });
1257
+ };
1258
+ SqlExecutor.prototype.insert = function (table, data) {
1259
+ return __awaiter(this, void 0, void 0, function () {
1260
+ var keys, values, placeholders, sql;
1261
+ var _this = this;
1262
+ return __generator(this, function (_a) {
1263
+ switch (_a.label) {
1264
+ case 0:
1265
+ keys = Object.keys(data);
1266
+ values = keys.map(function (k) { return data[k]; });
1267
+ placeholders = keys.map(function () { return '?'; }).join(', ');
1268
+ sql = "INSERT INTO `".concat(table, "` (").concat(keys.join(', '), ") VALUES (").concat(placeholders, ")");
1269
+ return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
1270
+ var result;
1271
+ return __generator(this, function (_a) {
1272
+ switch (_a.label) {
1273
+ case 0: return [4 /*yield*/, conn.execute(sql, values)];
1274
+ case 1:
1275
+ result = (_a.sent())[0];
1276
+ return [2 /*return*/, result];
1277
+ }
1278
+ });
1279
+ }); })];
1280
+ case 1: return [2 /*return*/, _a.sent()];
1281
+ }
1282
+ });
1283
+ });
1284
+ };
1285
+ SqlExecutor.prototype.update = function (table, primary, data) {
1286
+ return __awaiter(this, void 0, void 0, function () {
1287
+ var keys, values, updates, sql;
1288
+ var _this = this;
1289
+ return __generator(this, function (_a) {
1290
+ switch (_a.label) {
1291
+ case 0:
1292
+ if (!primary) {
1293
+ throw new Error('Primary key is required for update');
1382
1294
  }
1383
- if (C6.GET === requestMethod) {
1384
- if (undefined === query[C6.PAGINATION]) {
1385
- query[C6.PAGINATION] = {};
1386
- }
1387
- query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
1388
- query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
1295
+ keys = Object.keys(data);
1296
+ values = keys.map(function (k) { return data[k]; });
1297
+ updates = keys.map(function (k) { return "`".concat(k, "` = ?"); }).join(', ');
1298
+ sql = "UPDATE `".concat(table, "` SET ").concat(updates, " WHERE `").concat(primary, "` = ?");
1299
+ values.push(data[primary]);
1300
+ return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
1301
+ var result;
1302
+ return __generator(this, function (_a) {
1303
+ switch (_a.label) {
1304
+ case 0: return [4 /*yield*/, conn.execute(sql, values)];
1305
+ case 1:
1306
+ result = (_a.sent())[0];
1307
+ return [2 /*return*/, result];
1308
+ }
1309
+ });
1310
+ }); })];
1311
+ case 1: return [2 /*return*/, _a.sent()];
1312
+ }
1313
+ });
1314
+ });
1315
+ };
1316
+ SqlExecutor.prototype.delete = function (table, primary, args) {
1317
+ return __awaiter(this, void 0, void 0, function () {
1318
+ var sql;
1319
+ var _this = this;
1320
+ return __generator(this, function (_a) {
1321
+ switch (_a.label) {
1322
+ case 0:
1323
+ if (!primary || !(args === null || args === void 0 ? void 0 : args[primary])) {
1324
+ throw new Error('Primary key and value required for delete');
1389
1325
  }
1390
- return [4 /*yield*/, apiRequest()];
1326
+ sql = "DELETE FROM `".concat(table, "` WHERE `").concat(primary, "` = ?");
1327
+ return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
1328
+ var result;
1329
+ return __generator(this, function (_a) {
1330
+ switch (_a.label) {
1331
+ case 0: return [4 /*yield*/, conn.execute(sql, [args[primary]])];
1332
+ case 1:
1333
+ result = (_a.sent())[0];
1334
+ return [2 /*return*/, result];
1335
+ }
1336
+ });
1337
+ }); })];
1391
1338
  case 1: return [2 /*return*/, _a.sent()];
1392
1339
  }
1393
1340
  });
1394
1341
  });
1395
1342
  };
1396
- }
1343
+ return SqlExecutor;
1344
+ }(Executor));
1397
1345
 
1398
- function timeout(shouldContinueAfterTimeout, cb, timeoutMs) {
1399
- if (timeoutMs === void 0) { timeoutMs = 3000; }
1400
- var timer = function () { return setTimeout(function () {
1401
- if (false === shouldContinueAfterTimeout()) {
1402
- return;
1346
+ var SqlExecutor$1 = /*#__PURE__*/Object.freeze({
1347
+ __proto__: null,
1348
+ SqlExecutor: SqlExecutor
1349
+ });
1350
+
1351
+ function determineRuntimeJsType(mysqlType) {
1352
+ var base = mysqlType.toLowerCase().split('(')[0];
1353
+ if ([
1354
+ 'binary', 'varbinary', 'blob', 'tinyblob', 'mediumblob', 'longblob'
1355
+ ].includes(base))
1356
+ return 'buffer';
1357
+ if ([
1358
+ 'json', 'geometry', 'point', 'polygon', 'multipoint', 'multilinestring', 'multipolygon', 'geometrycollection'
1359
+ ].includes(base))
1360
+ return 'object';
1361
+ if ([
1362
+ 'tinyint', 'smallint', 'mediumint', 'int', 'integer', 'bigint',
1363
+ 'decimal', 'dec', 'numeric', 'float', 'double', 'real'
1364
+ ].includes(base))
1365
+ return 'number';
1366
+ if ([
1367
+ 'boolean', 'bool'
1368
+ ].includes(base))
1369
+ return 'boolean';
1370
+ return 'string';
1371
+ }
1372
+ function getPrimaryKeyTypes(table) {
1373
+ var _a;
1374
+ var result = {};
1375
+ var _loop_1 = function (key) {
1376
+ var fullKey = (_a = Object.entries(table.COLUMNS).find(function (_a) {
1377
+ _a[0]; var short = _a[1];
1378
+ return short === key;
1379
+ })) === null || _a === void 0 ? void 0 : _a[0];
1380
+ if (typeof fullKey === 'string') {
1381
+ var validation = table.TYPE_VALIDATION[fullKey];
1382
+ if (!validation)
1383
+ return "continue";
1384
+ result[key] = determineRuntimeJsType(validation.MYSQL_TYPE);
1403
1385
  }
1404
- cb();
1405
- }, timeoutMs); };
1406
- var timerId = timer();
1407
- return function () {
1408
- clearTimeout(timerId);
1409
1386
  };
1387
+ for (var _i = 0, _b = table.PRIMARY_SHORT; _i < _b.length; _i++) {
1388
+ var key = _b[_i];
1389
+ _loop_1(key);
1390
+ }
1391
+ return result;
1392
+ }
1393
+
1394
+ /**
1395
+ * Conditionally group a log if verbose.
1396
+ */
1397
+ function group(title, data) {
1398
+ if (!isVerbose)
1399
+ return;
1400
+ console.groupCollapsed("%c".concat(title), "color: #007acc");
1401
+ if (data !== undefined)
1402
+ console.log(data);
1403
+ console.groupEnd();
1404
+ }
1405
+ function info(message) {
1406
+ var optional = [];
1407
+ for (var _i = 1; _i < arguments.length; _i++) {
1408
+ optional[_i - 1] = arguments[_i];
1409
+ }
1410
+ if (!isVerbose)
1411
+ return;
1412
+ console.info.apply(console, __spreadArray(["%cINFO: ".concat(message), "color: #0a0"], optional, false));
1413
+ }
1414
+ function warn(message) {
1415
+ var optional = [];
1416
+ for (var _i = 1; _i < arguments.length; _i++) {
1417
+ optional[_i - 1] = arguments[_i];
1418
+ }
1419
+ console.warn.apply(console, __spreadArray(["%cWARN: ".concat(message), "color: #e90"], optional, false));
1420
+ }
1421
+ function error(message) {
1422
+ var optional = [];
1423
+ for (var _i = 1; _i < arguments.length; _i++) {
1424
+ optional[_i - 1] = arguments[_i];
1425
+ }
1426
+ console.error.apply(console, __spreadArray(["%cERROR: ".concat(message), "color: #c00"], optional, false));
1427
+ }
1428
+
1429
+ function checkAllRequestsComplete() {
1430
+ var stillRunning = apiRequestCache.filter(function (cache) { return undefined === cache.response; });
1431
+ if (stillRunning.length !== 0) {
1432
+ if (document === null || document === undefined) {
1433
+ throw new Error('document is undefined while waiting for API requests to complete (' + JSON.stringify(apiRequestCache) + ')');
1434
+ }
1435
+ // when requests return emtpy sets in full renders, it may not be possible to track their progress.
1436
+ console.warn('stillRunning...', stillRunning);
1437
+ return stillRunning.map(function (cache) { return cache.requestArgumentsSerialized; });
1438
+ }
1439
+ return true;
1440
+ }
1441
+
1442
+ function onSuccess(message) {
1443
+ toast.success(message, isDevelopment ? toastOptionsDevs : toastOptions);
1444
+ }
1445
+ function onError(message) {
1446
+ toast.error(message, isDevelopment ? toastOptionsDevs : toastOptions);
1410
1447
  }
1411
1448
 
1412
- export { C6Constants, CarbonSqlExecutor, DELETE, GET, POST, PUT, TestRestfulResponse, axiosInstance, checkAllRequestsComplete, clearCache, convertForRequestBody, eFetchDependencies, extendedTypeHints, getEnvVar, isDevelopment as isLocal, isNode, isPromise, isTest, isVerbose, removeInvalidKeys, removePrefixIfExists, restRequest, timeout, toastOptions, toastOptionsDevs };
1449
+ export { C6Constants, DELETE, Executor, GET, HttpExecutor, POST, PUT, SqlExecutor, TestRestfulResponse, apiRequestCache, axiosInstance, buildAggregateField, buildBooleanJoinedConditions, buildSelectQuery, checkAllRequestsComplete, checkCache, clearCache, convertForRequestBody, determineRuntimeJsType, eFetchDependencies, error, getEnvVar, getPrimaryKeyTypes, group, info, isDevelopment as isLocal, isNode, isPromise, isTest, isVerbose, onError, onSuccess, removeInvalidKeys, removePrefixIfExists, restRequest, sortAndSerializeQueryObject, timeout, toastOptions, toastOptionsDevs, userCustomClearCache, warn };
1413
1450
  //# sourceMappingURL=index.esm.js.map