@carbonorm/carbonnode 3.0.0 → 3.0.1

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 (41) 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 +18 -0
  4. package/dist/api/executors/HttpExecutor.d.ts +15 -0
  5. package/dist/api/executors/SqlExecutor.d.ts +11 -0
  6. package/dist/api/restRequest.d.ts +5 -164
  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 +223 -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/logger.d.ts +7 -0
  14. package/dist/api/utils/sortAndSerializeQueryObject.d.ts +1 -0
  15. package/dist/api/utils/testHelpers.d.ts +1 -0
  16. package/dist/api/utils/toastNotifier.d.ts +2 -0
  17. package/dist/index.cjs.js +614 -605
  18. package/dist/index.cjs.js.map +1 -1
  19. package/dist/index.d.ts +14 -2
  20. package/dist/index.esm.js +603 -607
  21. package/dist/index.esm.js.map +1 -1
  22. package/package.json +22 -6
  23. package/src/api/builders/sqlBuilder.ts +173 -0
  24. package/src/api/convertForRequestBody.ts +1 -2
  25. package/src/api/executors/Executor.ts +26 -0
  26. package/src/api/executors/HttpExecutor.ts +790 -0
  27. package/src/api/executors/SqlExecutor.ts +90 -0
  28. package/src/api/restRequest.ts +20 -1273
  29. package/src/api/types/dynamicFetching.ts +10 -0
  30. package/src/api/types/modifyTypes.ts +25 -0
  31. package/src/api/types/mysqlTypes.ts +33 -0
  32. package/src/api/types/ormInterfaces.ts +287 -0
  33. package/src/api/utils/apiHelpers.ts +83 -0
  34. package/src/api/utils/cacheManager.ts +67 -0
  35. package/src/api/utils/logger.ts +24 -0
  36. package/src/api/utils/sortAndSerializeQueryObject.ts +12 -0
  37. package/src/api/utils/testHelpers.ts +24 -0
  38. package/src/api/utils/toastNotifier.ts +11 -0
  39. package/src/index.ts +14 -2
  40. package/src/api/carbonSqlExecutor.ts +0 -279
  41. 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,39 @@ 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
+ function extendedTypeHints() {
578
+ return function (argv) { return restRequest(argv); };
579
+ }
580
+
693
581
  var toastOptions = {
694
582
  position: "bottom-left",
695
583
  autoClose: 10000,
@@ -730,6 +618,12 @@ function TestRestfulResponse(response, success, error) {
730
618
  }
731
619
  return false;
732
620
  }
621
+ function removePrefixIfExists(tableName, prefix) {
622
+ if (tableName.startsWith(prefix.toLowerCase())) {
623
+ return tableName.slice(prefix.length);
624
+ }
625
+ return tableName;
626
+ }
733
627
  function removeInvalidKeys(request, c6Tables) {
734
628
  var intersection = {};
735
629
  var restfulObjectKeys = [];
@@ -747,32 +641,17 @@ function removeInvalidKeys(request, c6Tables) {
747
641
  isTest || console.log('intersection', intersection);
748
642
  return intersection;
749
643
  }
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 = {}));
644
+
761
645
  // do not remove entries from this array. It is used to track the progress of API requests.
762
646
  // position in array is important. Do not sort. To not add to begging.
763
647
  var apiRequestCache = [];
764
648
  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; });
649
+ function clearCache(props) {
650
+ if (false === (props === null || props === void 0 ? void 0 : props.ignoreWarning)) {
651
+ console.warn('The rest api clearCache should only be used with extreme care! Avoid using this in favor of using `cacheResults : boolean`.');
774
652
  }
775
- return true;
653
+ userCustomClearCache.map(function (f) { return 'function' === typeof f && f(); });
654
+ userCustomClearCache = apiRequestCache = [];
776
655
  }
777
656
  function checkCache(cacheResult, requestMethod, tableName, request) {
778
657
  var _a, _b, _c;
@@ -789,92 +668,88 @@ function checkCache(cacheResult, requestMethod, tableName, request) {
789
668
  console.log('%c ' + requestMethod + ' ' + tableName, 'color: #cc0');
790
669
  console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #cc0', request);
791
670
  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
- function clearCache(props) {
806
- if (false === (props === null || props === void 0 ? void 0 : props.ignoreWarning)) {
807
- console.warn('The rest api clearCache should only be used with extreme care! Avoid using this in favor of using `cacheResults : boolean`.');
808
- }
809
- userCustomClearCache.map(function (f) { return 'function' === typeof f && f(); });
810
- userCustomClearCache = apiRequestCache = [];
811
- }
812
- function removePrefixIfExists(tableName, prefix) {
813
- if (tableName.startsWith(prefix.toLowerCase())) {
814
- return tableName.slice(prefix.length);
671
+ console.groupEnd();
672
+ }
673
+ return undefined;
815
674
  }
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;
675
+ return false;
834
676
  }
835
- function extendedTypeHints() {
836
- return function (argv) { return restRequest(argv); };
677
+
678
+ function sortAndSerializeQueryObject(tables, query) {
679
+ var orderedQuery = Object.keys(query).sort().reduce(function (obj, key) {
680
+ obj[key] = query[key];
681
+ return obj;
682
+ }, {});
683
+ return tables + ' ' + JSON.stringify(orderedQuery);
837
684
  }
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;
685
+
686
+ var HttpExecutor = /** @class */ (function (_super) {
687
+ __extends(HttpExecutor, _super);
688
+ function HttpExecutor() {
689
+ return _super !== null && _super.apply(this, arguments) || this;
856
690
  }
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);
691
+ HttpExecutor.prototype.execute = function () {
692
+ return __awaiter(this, void 0, void 0, function () {
693
+ var _a, C6, axios, restURL, withCredentials, tableName, requestMethod, queryCallback, responseCallback, skipPrimaryCheck, clearCache, fullTableList, operatingTableFullName, operatingTable, tables, query, apiRequest;
694
+ var _this = this;
695
+ return __generator(this, function (_b) {
696
+ switch (_b.label) {
697
+ case 0:
698
+ _a = this.config, C6 = _a.C6, axios = _a.axios, restURL = _a.restURL, withCredentials = _a.withCredentials, tableName = _a.tableName, requestMethod = _a.requestMethod, queryCallback = _a.queryCallback, responseCallback = _a.responseCallback, skipPrimaryCheck = _a.skipPrimaryCheck, clearCache = _a.clearCache;
699
+ fullTableList = Array.isArray(tableName) ? tableName : [tableName];
700
+ operatingTableFullName = fullTableList[0];
701
+ operatingTable = removePrefixIfExists(operatingTableFullName, C6.PREFIX);
702
+ tables = fullTableList.join(',');
703
+ switch (requestMethod) {
704
+ case GET:
705
+ case POST:
706
+ case PUT:
707
+ case DELETE:
708
+ break;
709
+ default:
710
+ throw Error('Bad request method passed to getApi');
711
+ }
712
+ if (null !== clearCache || undefined !== clearCache) {
713
+ userCustomClearCache[tables + requestMethod] = clearCache;
714
+ }
715
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request for (' + tableName + ')', 'color: #0c0');
716
+ console.log('request', this.request);
717
+ console.groupEnd();
718
+ if ('function' === typeof queryCallback) {
719
+ query = queryCallback(this.request); // obj or obj[]
720
+ }
721
+ else {
722
+ query = queryCallback;
723
+ }
724
+ if (undefined === query || null === query) {
725
+ if (this.request.debug && isDevelopment) {
726
+ toast.warning("DEV: queryCallback returned undefined, signaling in Custom Cache. (returning null)", toastOptionsDevs);
727
+ }
728
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + tableName + ') undefined, returning null (will not fire ajax)!', 'color: #c00');
729
+ 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');
730
+ console.trace();
731
+ console.groupEnd();
732
+ return [2 /*return*/, null];
733
+ }
734
+ if (C6.GET === requestMethod) {
735
+ if (undefined === query[C6.PAGINATION]) {
736
+ query[C6.PAGINATION] = {};
737
+ }
738
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
739
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
740
+ }
741
+ apiRequest = function () { return __awaiter(_this, void 0, void 0, function () {
742
+ 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;
743
+ var _e;
744
+ var _this = this;
745
+ var _f, _g, _h, _j, _k, _l;
746
+ return __generator(this, function (_m) {
747
+ _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
748
  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])
749
+ && undefined !== ((_f = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _f === void 0 ? void 0 : _f[C6.PAGE])
875
750
  && 1 !== query[C6.PAGINATION][C6.PAGE]) {
876
751
  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);
752
+ console.log('Request Data (note you may see the success and/or error prompt):', this.request);
878
753
  console.trace();
879
754
  console.groupEnd();
880
755
  }
@@ -892,11 +767,11 @@ function restRequest(_a) {
892
767
  query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
893
768
  query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
894
769
  // this will evaluate true most the time
895
- if (true === request.cacheResults) {
770
+ if (true === cacheResults) {
896
771
  // just find the next, non-fetched, page and return a function to request it
897
772
  if (undefined !== cacheResult) {
898
773
  do {
899
- cacheCheck = checkCache(cacheResult, requestMethod, tableName, request);
774
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
900
775
  if (false !== cacheCheck) {
901
776
  return [2 /*return*/, cacheCheck];
902
777
  }
@@ -906,7 +781,7 @@ function restRequest(_a) {
906
781
  querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
907
782
  cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
908
783
  } while (undefined !== cacheResult);
909
- if (request.debug && isDevelopment) {
784
+ if (debug && isDevelopment) {
910
785
  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
786
  }
912
787
  // @ts-ignore - this is an incorrect warning on TS, it's well typed
@@ -915,17 +790,17 @@ function restRequest(_a) {
915
790
  cachingConfirmed = true;
916
791
  }
917
792
  else {
918
- if (request.debug && isDevelopment) {
793
+ if (debug && isDevelopment) {
919
794
  toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
920
795
  }
921
796
  }
922
- if (request.debug && isDevelopment) {
797
+ if (debug && isDevelopment) {
923
798
  toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
924
799
  }
925
800
  }
926
- else if (request.cacheResults) { // if we are not getting, we are updating, deleting, or inserting
801
+ else if (cacheResults) { // if we are not getting, we are updating, deleting, or inserting
927
802
  if (cacheResult) {
928
- cacheCheck = checkCache(cacheResult, requestMethod, tableName, request);
803
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
929
804
  if (false !== cacheCheck) {
930
805
  return [2 /*return*/, cacheCheck];
931
806
  }
@@ -938,7 +813,7 @@ function restRequest(_a) {
938
813
  needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
939
814
  && false === skipPrimaryCheck;
940
815
  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();
816
+ 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
817
  if (needsConditionOrPrimaryCheck) {
943
818
  if (undefined === primaryKey) {
944
819
  if (null === query
@@ -948,17 +823,17 @@ function restRequest(_a) {
948
823
  || query[C6.WHERE].length === 0)
949
824
  || (Object.keys(query === null || query === void 0 ? void 0 : query[C6.WHERE]).length === 0)) {
950
825
  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 + ').');
826
+ 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
827
  }
953
828
  }
954
829
  else {
955
830
  if (undefined === query
956
831
  || null === query
957
832
  || false === primaryKey in query) {
958
- if (true === request.debug && isDevelopment) {
833
+ if (true === debug && isDevelopment) {
959
834
  toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
960
835
  }
961
- throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
836
+ throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(this.request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
962
837
  }
963
838
  if (undefined === (query === null || query === void 0 ? void 0 : query[primaryKey])
964
839
  || null === (query === null || query === void 0 ? void 0 : query[primaryKey])) {
@@ -967,55 +842,6 @@ function restRequest(_a) {
967
842
  }
968
843
  }
969
844
  }
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
845
  // A part of me exists that wants to remove this, but it's a good feature
1020
846
  // this allows developers the ability to cache requests based on primary key
1021
847
  // for tables like `photos` this can be a huge performance boost
@@ -1037,12 +863,12 @@ function restRequest(_a) {
1037
863
  }
1038
864
  try {
1039
865
  console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
1040
- console.log(request);
866
+ console.log(this.request);
1041
867
  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
868
  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
869
  console.trace();
1044
870
  console.groupEnd();
1045
- axiosActiveRequest = axios[requestMethod.toLowerCase()].apply(axios, __spreadArray([restRequestUri], ((function () {
871
+ axiosActiveRequest = (_e = axios)[requestMethod.toLowerCase()].apply(_e, __spreadArray([restRequestUri], ((function () {
1046
872
  // @link - https://axios-http.com/docs/instance
1047
873
  // How configuration vs data is passed is variable, use documentation above for reference
1048
874
  if (requestMethod === GET) {
@@ -1052,9 +878,9 @@ function restRequest(_a) {
1052
878
  }];
1053
879
  }
1054
880
  else if (requestMethod === POST) {
1055
- if (undefined !== (request === null || request === void 0 ? void 0 : request.dataInsertMultipleRows)) {
881
+ if (undefined !== dataInsertMultipleRows) {
1056
882
  return [
1057
- request.dataInsertMultipleRows.map(function (data) {
883
+ dataInsertMultipleRows.map(function (data) {
1058
884
  return convertForRequestBody(data, fullTableList, C6, function (message) { return toast.error(message, toastOptions); });
1059
885
  }),
1060
886
  {
@@ -1100,11 +926,11 @@ function restRequest(_a) {
1100
926
  // returning the promise with this then is important for tests. todo - we could make that optional.
1101
927
  // https://rapidapi.com/guides/axios-async-await
1102
928
  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;
929
+ var cacheIndex, responseData_1, dependencies_1, fetchReferences_1, apiRequestPromises, _loop_1, _a, _b, _c, _i, tableToFetch;
1104
930
  var _this = this;
1105
- var _d, _e, _f, _g, _h, _j, _k, _l, _m;
1106
- return __generator(this, function (_o) {
1107
- switch (_o.label) {
931
+ var _d, _e, _f, _g, _h, _j, _k;
932
+ return __generator(this, function (_l) {
933
+ switch (_l.label) {
1108
934
  case 0:
1109
935
  if (typeof response.data === 'string') {
1110
936
  if (isTest) {
@@ -1119,40 +945,38 @@ function restRequest(_a) {
1119
945
  // only cache get method requests
1120
946
  apiRequestCache[cacheIndex].response = response;
1121
947
  }
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!");
948
+ apiResponse = TestRestfulResponse(response, success, error);
1123
949
  if (false === apiResponse) {
1124
- if (request.debug && isDevelopment) {
950
+ if (debug && isDevelopment) {
1125
951
  toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
1126
952
  }
1127
953
  return [2 /*return*/, response];
1128
954
  }
1129
955
  // stateful operations are done in the response callback - its leverages rest generated functions
1130
956
  if (responseCallback) {
1131
- responseCallback(response, request, apiResponse);
957
+ responseCallback(response, this.request, apiResponse);
1132
958
  }
1133
959
  if (!(C6.GET === requestMethod)) return [3 /*break*/, 6];
1134
960
  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;
961
+ returnGetNextPageFunction = 1 !== ((_d = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _d === void 0 ? void 0 : _d[C6.LIMIT]) &&
962
+ ((_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
963
  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');
964
+ 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
965
  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);
966
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', this.request);
1141
967
  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);
968
+ 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
969
  console.trace();
1144
970
  console.groupEnd();
1145
971
  }
1146
972
  if (false === returnGetNextPageFunction
1147
- && true === request.debug
973
+ && true === debug
1148
974
  && 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);
975
+ 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
976
  }
1151
- (_m = request.fetchDependencies) !== null && _m !== void 0 ? _m : (request.fetchDependencies = eFetchDependencies.NONE);
1152
- if (!(request.fetchDependencies
1153
- && 'number' === typeof request.fetchDependencies
977
+ if (!(fetchDependencies
978
+ && 'number' === typeof fetchDependencies
1154
979
  && responseData_1.rest.length > 0)) return [3 /*break*/, 6];
1155
- fetchDependencies = request.fetchDependencies;
1156
980
  console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
1157
981
  + (fetchDependencies & eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
1158
982
  + (fetchDependencies & eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
@@ -1223,9 +1047,9 @@ function restRequest(_a) {
1223
1047
  console.log('fetchReferences', fetchReferences_1);
1224
1048
  _loop_1 = function (tableToFetch) {
1225
1049
  var referencesTables, shouldContinue, fetchTable, RestApi, nextFetchDependencies;
1226
- var _p;
1227
- return __generator(this, function (_q) {
1228
- switch (_q.label) {
1050
+ var _m;
1051
+ return __generator(this, function (_o) {
1052
+ switch (_o.label) {
1229
1053
  case 0:
1230
1054
  if (fetchDependencies & eFetchDependencies.C6ENTITY
1231
1055
  && 'string' === typeof tableName
@@ -1245,7 +1069,7 @@ function restRequest(_a) {
1245
1069
  }
1246
1070
  return [4 /*yield*/, C6.IMPORT(tableToFetch)];
1247
1071
  case 1:
1248
- fetchTable = _q.sent();
1072
+ fetchTable = _o.sent();
1249
1073
  RestApi = fetchTable.default;
1250
1074
  console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff');
1251
1075
  nextFetchDependencies = eFetchDependencies.NONE;
@@ -1268,8 +1092,8 @@ function restRequest(_a) {
1268
1092
  // it not certain that they are using carbons' entities either
1269
1093
  // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
1270
1094
  // 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] = {
1095
+ apiRequestPromises.push(RestApi.Get((_m = {},
1096
+ _m[C6.WHERE] = {
1273
1097
  0: Object.keys(fetchReferences_1[tableToFetch]).reduce(function (sum, column) {
1274
1098
  fetchReferences_1[tableToFetch][column] = fetchReferences_1[tableToFetch][column].flat(Infinity);
1275
1099
  if (0 === fetchReferences_1[tableToFetch][column].length) {
@@ -1284,8 +1108,8 @@ function restRequest(_a) {
1284
1108
  return sum;
1285
1109
  }, {})
1286
1110
  },
1287
- _p.fetchDependencies = nextFetchDependencies,
1288
- _p)));
1111
+ _m.fetchDependencies = nextFetchDependencies,
1112
+ _m)));
1289
1113
  return [2 /*return*/];
1290
1114
  }
1291
1115
  });
@@ -1295,7 +1119,7 @@ function restRequest(_a) {
1295
1119
  for (_c in _a)
1296
1120
  _b.push(_c);
1297
1121
  _i = 0;
1298
- _o.label = 1;
1122
+ _l.label = 1;
1299
1123
  case 1:
1300
1124
  if (!(_i < _b.length)) return [3 /*break*/, 4];
1301
1125
  _c = _b[_i];
@@ -1303,8 +1127,8 @@ function restRequest(_a) {
1303
1127
  tableToFetch = _c;
1304
1128
  return [5 /*yield**/, _loop_1(tableToFetch)];
1305
1129
  case 2:
1306
- _o.sent();
1307
- _o.label = 3;
1130
+ _l.sent();
1131
+ _l.label = 3;
1308
1132
  case 3:
1309
1133
  _i++;
1310
1134
  return [3 /*break*/, 1];
@@ -1312,16 +1136,17 @@ function restRequest(_a) {
1312
1136
  console.groupEnd();
1313
1137
  return [4 /*yield*/, Promise.all(apiRequestPromises)];
1314
1138
  case 5:
1315
- _o.sent();
1139
+ _l.sent();
1316
1140
  apiRequestPromises.map(function (promise) { return __awaiter(_this, void 0, void 0, function () {
1317
1141
  var _a, _b;
1318
1142
  return __generator(this, function (_c) {
1319
1143
  switch (_c.label) {
1320
1144
  case 0:
1321
- if (!Array.isArray(request.fetchDependencies)) {
1322
- request.fetchDependencies = [];
1145
+ if (!Array.isArray(this.request.fetchDependencies)) {
1146
+ // to reassign value we must ref the root
1147
+ this.request.fetchDependencies = [];
1323
1148
  }
1324
- _b = (_a = request.fetchDependencies).push;
1149
+ _b = (_a = this.request.fetchDependencies).push;
1325
1150
  return [4 /*yield*/, promise];
1326
1151
  case 1:
1327
1152
  _b.apply(_a, [_c.sent()]);
@@ -1329,9 +1154,9 @@ function restRequest(_a) {
1329
1154
  }
1330
1155
  });
1331
1156
  }); });
1332
- _o.label = 6;
1157
+ _l.label = 6;
1333
1158
  case 6:
1334
- if (request.debug && isDevelopment) {
1159
+ if (debug && isDevelopment) {
1335
1160
  toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1336
1161
  }
1337
1162
  return [2 /*return*/, response];
@@ -1339,75 +1164,246 @@ function restRequest(_a) {
1339
1164
  });
1340
1165
  }); })];
1341
1166
  }
1342
- catch (error) {
1167
+ catch (throwableError) {
1343
1168
  if (isTest) {
1344
- throw new Error(JSON.stringify(error));
1169
+ throw new Error(JSON.stringify(throwableError));
1345
1170
  }
1346
1171
  console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
1347
1172
  console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
1348
- console.warn(error);
1173
+ console.warn(throwableError);
1349
1174
  console.trace();
1350
1175
  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!");
1176
+ TestRestfulResponse(throwableError, success, error);
1352
1177
  return [2 /*return*/, null];
1353
1178
  }
1354
1179
  return [2 /*return*/];
1355
- }
1356
- });
1357
- });
1358
- }
1359
- var query;
1360
- if (request === void 0) { request = {}; }
1180
+ });
1181
+ }); };
1182
+ return [4 /*yield*/, apiRequest()];
1183
+ case 1: return [2 /*return*/, _b.sent()];
1184
+ }
1185
+ });
1186
+ });
1187
+ };
1188
+ return HttpExecutor;
1189
+ }(Executor));
1190
+
1191
+ var HttpExecutor$1 = /*#__PURE__*/Object.freeze({
1192
+ __proto__: null,
1193
+ HttpExecutor: HttpExecutor
1194
+ });
1195
+
1196
+ var SqlExecutor = /** @class */ (function (_super) {
1197
+ __extends(SqlExecutor, _super);
1198
+ function SqlExecutor() {
1199
+ return _super !== null && _super.apply(this, arguments) || this;
1200
+ }
1201
+ SqlExecutor.prototype.execute = function () {
1202
+ switch (this.config.requestMethod) {
1203
+ case 'GET':
1204
+ return this.select(this.config.tableName, undefined, this.request).then(function (rows) { return ({ rest: rows }); });
1205
+ case 'POST':
1206
+ return this.insert(this.config.tableName, this.request);
1207
+ case 'PUT':
1208
+ return this.update(this.config.tableName, undefined, this.request);
1209
+ case 'DELETE':
1210
+ return this.delete(this.config.tableName, undefined, this.request);
1211
+ }
1212
+ };
1213
+ SqlExecutor.prototype.withConnection = function (cb) {
1214
+ return __awaiter(this, void 0, void 0, function () {
1215
+ var conn;
1216
+ return __generator(this, function (_a) {
1217
+ switch (_a.label) {
1218
+ case 0: return [4 /*yield*/, this.config.mysqlPool.getConnection()];
1219
+ case 1:
1220
+ conn = _a.sent();
1221
+ _a.label = 2;
1222
+ case 2:
1223
+ _a.trys.push([2, , 4, 5]);
1224
+ return [4 /*yield*/, cb(conn)];
1225
+ case 3: return [2 /*return*/, _a.sent()];
1226
+ case 4:
1227
+ conn.release();
1228
+ return [7 /*endfinally*/];
1229
+ case 5: return [2 /*return*/];
1230
+ }
1231
+ });
1232
+ });
1233
+ };
1234
+ SqlExecutor.prototype.select = function (table, primary, args) {
1235
+ return __awaiter(this, void 0, void 0, function () {
1236
+ var sql;
1237
+ var _this = this;
1361
1238
  return __generator(this, function (_a) {
1362
1239
  switch (_a.label) {
1363
1240
  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];
1241
+ sql = buildSelectQuery(table, primary, args);
1242
+ return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
1243
+ var rows;
1244
+ return __generator(this, function (_a) {
1245
+ switch (_a.label) {
1246
+ case 0:
1247
+ console.log(sql);
1248
+ return [4 /*yield*/, conn.query(sql)];
1249
+ case 1:
1250
+ rows = (_a.sent())[0];
1251
+ return [2 /*return*/, rows];
1252
+ }
1253
+ });
1254
+ }); })];
1255
+ case 1: return [2 /*return*/, _a.sent()];
1256
+ }
1257
+ });
1258
+ });
1259
+ };
1260
+ SqlExecutor.prototype.insert = function (table, data) {
1261
+ return __awaiter(this, void 0, void 0, function () {
1262
+ var keys, values, placeholders, sql;
1263
+ var _this = this;
1264
+ return __generator(this, function (_a) {
1265
+ switch (_a.label) {
1266
+ case 0:
1267
+ keys = Object.keys(data);
1268
+ values = keys.map(function (k) { return data[k]; });
1269
+ placeholders = keys.map(function () { return '?'; }).join(', ');
1270
+ sql = "INSERT INTO `".concat(table, "` (").concat(keys.join(', '), ") VALUES (").concat(placeholders, ")");
1271
+ return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
1272
+ var result;
1273
+ return __generator(this, function (_a) {
1274
+ switch (_a.label) {
1275
+ case 0: return [4 /*yield*/, conn.execute(sql, values)];
1276
+ case 1:
1277
+ result = (_a.sent())[0];
1278
+ return [2 /*return*/, result];
1279
+ }
1280
+ });
1281
+ }); })];
1282
+ case 1: return [2 /*return*/, _a.sent()];
1283
+ }
1284
+ });
1285
+ });
1286
+ };
1287
+ SqlExecutor.prototype.update = function (table, primary, data) {
1288
+ return __awaiter(this, void 0, void 0, function () {
1289
+ var keys, values, updates, sql;
1290
+ var _this = this;
1291
+ return __generator(this, function (_a) {
1292
+ switch (_a.label) {
1293
+ case 0:
1294
+ if (!primary) {
1295
+ throw new Error('Primary key is required for update');
1382
1296
  }
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;
1297
+ keys = Object.keys(data);
1298
+ values = keys.map(function (k) { return data[k]; });
1299
+ updates = keys.map(function (k) { return "`".concat(k, "` = ?"); }).join(', ');
1300
+ sql = "UPDATE `".concat(table, "` SET ").concat(updates, " WHERE `").concat(primary, "` = ?");
1301
+ values.push(data[primary]);
1302
+ return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
1303
+ var result;
1304
+ return __generator(this, function (_a) {
1305
+ switch (_a.label) {
1306
+ case 0: return [4 /*yield*/, conn.execute(sql, values)];
1307
+ case 1:
1308
+ result = (_a.sent())[0];
1309
+ return [2 /*return*/, result];
1310
+ }
1311
+ });
1312
+ }); })];
1313
+ case 1: return [2 /*return*/, _a.sent()];
1314
+ }
1315
+ });
1316
+ });
1317
+ };
1318
+ SqlExecutor.prototype.delete = function (table, primary, args) {
1319
+ return __awaiter(this, void 0, void 0, function () {
1320
+ var sql;
1321
+ var _this = this;
1322
+ return __generator(this, function (_a) {
1323
+ switch (_a.label) {
1324
+ case 0:
1325
+ if (!primary || !(args === null || args === void 0 ? void 0 : args[primary])) {
1326
+ throw new Error('Primary key and value required for delete');
1389
1327
  }
1390
- return [4 /*yield*/, apiRequest()];
1328
+ sql = "DELETE FROM `".concat(table, "` WHERE `").concat(primary, "` = ?");
1329
+ return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
1330
+ var result;
1331
+ return __generator(this, function (_a) {
1332
+ switch (_a.label) {
1333
+ case 0: return [4 /*yield*/, conn.execute(sql, [args[primary]])];
1334
+ case 1:
1335
+ result = (_a.sent())[0];
1336
+ return [2 /*return*/, result];
1337
+ }
1338
+ });
1339
+ }); })];
1391
1340
  case 1: return [2 /*return*/, _a.sent()];
1392
1341
  }
1393
1342
  });
1394
1343
  });
1395
1344
  };
1345
+ return SqlExecutor;
1346
+ }(Executor));
1347
+
1348
+ var SqlExecutor$1 = /*#__PURE__*/Object.freeze({
1349
+ __proto__: null,
1350
+ SqlExecutor: SqlExecutor
1351
+ });
1352
+
1353
+ /**
1354
+ * Conditionally group a log if verbose.
1355
+ */
1356
+ function group(title, data) {
1357
+ if (!isVerbose)
1358
+ return;
1359
+ console.groupCollapsed("%c".concat(title), "color: #007acc");
1360
+ if (data !== undefined)
1361
+ console.log(data);
1362
+ console.groupEnd();
1363
+ }
1364
+ function info(message) {
1365
+ var optional = [];
1366
+ for (var _i = 1; _i < arguments.length; _i++) {
1367
+ optional[_i - 1] = arguments[_i];
1368
+ }
1369
+ if (!isVerbose)
1370
+ return;
1371
+ console.info.apply(console, __spreadArray(["%cINFO: ".concat(message), "color: #0a0"], optional, false));
1372
+ }
1373
+ function warn(message) {
1374
+ var optional = [];
1375
+ for (var _i = 1; _i < arguments.length; _i++) {
1376
+ optional[_i - 1] = arguments[_i];
1377
+ }
1378
+ console.warn.apply(console, __spreadArray(["%cWARN: ".concat(message), "color: #e90"], optional, false));
1379
+ }
1380
+ function error(message) {
1381
+ var optional = [];
1382
+ for (var _i = 1; _i < arguments.length; _i++) {
1383
+ optional[_i - 1] = arguments[_i];
1384
+ }
1385
+ console.error.apply(console, __spreadArray(["%cERROR: ".concat(message), "color: #c00"], optional, false));
1396
1386
  }
1397
1387
 
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;
1388
+ function checkAllRequestsComplete() {
1389
+ var stillRunning = apiRequestCache.filter(function (cache) { return undefined === cache.response; });
1390
+ if (stillRunning.length !== 0) {
1391
+ if (document === null || document === undefined) {
1392
+ throw new Error('document is undefined while waiting for API requests to complete (' + JSON.stringify(apiRequestCache) + ')');
1403
1393
  }
1404
- cb();
1405
- }, timeoutMs); };
1406
- var timerId = timer();
1407
- return function () {
1408
- clearTimeout(timerId);
1409
- };
1394
+ // when requests return emtpy sets in full renders, it may not be possible to track their progress.
1395
+ console.warn('stillRunning...', stillRunning);
1396
+ return stillRunning.map(function (cache) { return cache.requestArgumentsSerialized; });
1397
+ }
1398
+ return true;
1399
+ }
1400
+
1401
+ function onSuccess(message) {
1402
+ toast.success(message, isDevelopment ? toastOptionsDevs : toastOptions);
1403
+ }
1404
+ function onError(message) {
1405
+ toast.error(message, isDevelopment ? toastOptionsDevs : toastOptions);
1410
1406
  }
1411
1407
 
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 };
1408
+ export { C6Constants, DELETE, Executor, GET, HttpExecutor, POST, PUT, SqlExecutor, TestRestfulResponse, apiRequestCache, axiosInstance, buildAggregateField, buildBooleanJoinedConditions, buildSelectQuery, checkAllRequestsComplete, checkCache, clearCache, convertForRequestBody, eFetchDependencies, error, extendedTypeHints, getEnvVar, group, info, isDevelopment as isLocal, isNode, isPromise, isTest, isVerbose, onError, onSuccess, removeInvalidKeys, removePrefixIfExists, restRequest, sortAndSerializeQueryObject, timeout, toastOptions, toastOptionsDevs, userCustomClearCache, warn };
1413
1409
  //# sourceMappingURL=index.esm.js.map