@carbonorm/carbonnode 3.7.13 → 3.7.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import axios from 'axios';
2
2
  import Qs from 'qs';
3
- import { __assign, __awaiter, __generator, __extends, __spreadArray, __rest } from 'tslib';
3
+ import { __assign, __awaiter, __generator, __spreadArray, __rest, __extends } from 'tslib';
4
4
  import { toast } from 'react-toastify';
5
5
  import namedPlaceholders from 'named-placeholders';
6
6
  import { Buffer as Buffer$1 } from 'buffer';
7
+ import express from 'express';
7
8
 
8
9
  var C6Constants = {
9
10
  // try to 1=1 match the Rest abstract class
@@ -620,6 +621,122 @@ function sortAndSerializeQueryObject(tables, query) {
620
621
  return tables + ' ' + JSON.stringify(orderedQuery);
621
622
  }
622
623
 
624
+ /**
625
+ * Converts a singular T-shaped request into complex ORM format for GET/PUT/DELETE
626
+ * Enforces that all primary keys are present for singular syntax and that the table has PKs.
627
+ * Optionally accepts a previously removed primary key (key/value) to reconstruct WHERE.
628
+ */
629
+ function normalizeSingularRequest(requestMethod, request, restModel, removedPrimary) {
630
+ var _a, _b;
631
+ var _c;
632
+ if (request == null || typeof request !== 'object')
633
+ return request;
634
+ var specialKeys = new Set([
635
+ C6Constants.SELECT,
636
+ C6Constants.UPDATE,
637
+ C6Constants.DELETE,
638
+ C6Constants.WHERE,
639
+ C6Constants.JOIN,
640
+ C6Constants.PAGINATION,
641
+ ]);
642
+ // Determine if the request is already complex (has any special key besides PAGINATION)
643
+ var keys = Object.keys(request);
644
+ var hasComplexKeys = keys.some(function (k) { return k !== C6Constants.PAGINATION && specialKeys.has(k); });
645
+ if (hasComplexKeys)
646
+ return request; // already complex
647
+ // We treat it as singular when it's not complex.
648
+ // For GET, PUT, DELETE only
649
+ if (!(requestMethod === C6Constants.GET || requestMethod === C6Constants.PUT || requestMethod === C6Constants.DELETE)) {
650
+ return request;
651
+ }
652
+ var pkShorts = Array.isArray(restModel.PRIMARY_SHORT) ? __spreadArray([], restModel.PRIMARY_SHORT, true) : [];
653
+ var pkFulls = Array.isArray(restModel.PRIMARY) ? __spreadArray([], restModel.PRIMARY, true) : [];
654
+ var resolveShortKey = function (key) {
655
+ var _a;
656
+ var cols = restModel.COLUMNS || {};
657
+ return (_a = cols[key]) !== null && _a !== void 0 ? _a : key;
658
+ };
659
+ if (!pkShorts.length) {
660
+ // For GET requests, do not enforce primary key presence; treat as a collection query.
661
+ if (requestMethod === C6Constants.GET)
662
+ return request;
663
+ throw new Error("Table (".concat(restModel.TABLE_NAME, ") has no primary key; singular request syntax is not allowed."));
664
+ }
665
+ // Build pk map from request + possibly removed primary key (accept short or fully-qualified keys)
666
+ var pkValues = {};
667
+ var requestObj = request;
668
+ var _loop_1 = function (pkShort) {
669
+ // 1) direct short key
670
+ var value = requestObj[pkShort];
671
+ if (value === undefined) {
672
+ // 2) fully-qualified key matching this short key (from PRIMARY list or by concatenation)
673
+ var fqCandidate_1 = "".concat(restModel.TABLE_NAME, ".").concat(pkShort);
674
+ var fqKey = (_c = pkFulls.find(function (fq) { return fq === fqCandidate_1 || fq.endsWith(".".concat(pkShort)); })) !== null && _c !== void 0 ? _c : fqCandidate_1;
675
+ value = requestObj[fqKey];
676
+ }
677
+ if (value === undefined && removedPrimary) {
678
+ // 3) removedPrimary may provide either short or fully-qualified key
679
+ var removedKeyShort = resolveShortKey(removedPrimary.key);
680
+ if (removedKeyShort === pkShort)
681
+ value = removedPrimary.value;
682
+ }
683
+ if (value !== undefined && value !== null) {
684
+ pkValues[pkShort] = value;
685
+ }
686
+ };
687
+ for (var _i = 0, pkShorts_1 = pkShorts; _i < pkShorts_1.length; _i++) {
688
+ var pkShort = pkShorts_1[_i];
689
+ _loop_1(pkShort);
690
+ }
691
+ var missing = pkShorts.filter(function (pk) { return !(pk in pkValues); });
692
+ if (missing.length) {
693
+ // For GET requests, if not all PKs are provided, treat as a collection query and leave as-is.
694
+ if (requestMethod === C6Constants.GET) {
695
+ return request;
696
+ }
697
+ throw new Error("Singular request requires all primary key(s) [".concat(pkShorts.join(', '), "] for table (").concat(restModel.TABLE_NAME, "). Missing: [").concat(missing.join(', '), "]"));
698
+ }
699
+ // Strip API metadata that should remain at root
700
+ var _d = request, dataInsertMultipleRows = _d.dataInsertMultipleRows, cacheResults = _d.cacheResults, fetchDependencies = _d.fetchDependencies, debug = _d.debug, success = _d.success, error = _d.error, rest = __rest(_d, ["dataInsertMultipleRows", "cacheResults", "fetchDependencies", "debug", "success", "error"]);
701
+ if (requestMethod === C6Constants.GET) {
702
+ var normalized_1 = {
703
+ WHERE: __assign({}, pkValues),
704
+ };
705
+ // Preserve pagination if any was added previously
706
+ if (request[C6Constants.PAGINATION]) {
707
+ normalized_1[C6Constants.PAGINATION] = request[C6Constants.PAGINATION];
708
+ }
709
+ return __assign(__assign({}, normalized_1), { dataInsertMultipleRows: dataInsertMultipleRows, cacheResults: cacheResults, fetchDependencies: fetchDependencies, debug: debug, success: success, error: error });
710
+ }
711
+ if (requestMethod === C6Constants.DELETE) {
712
+ var normalized_2 = (_a = {},
713
+ _a[C6Constants.DELETE] = true,
714
+ _a.WHERE = __assign({}, pkValues),
715
+ _a);
716
+ return __assign(__assign({}, normalized_2), { dataInsertMultipleRows: dataInsertMultipleRows, cacheResults: cacheResults, fetchDependencies: fetchDependencies, debug: debug, success: success, error: error });
717
+ }
718
+ // PUT
719
+ var updateBody = {};
720
+ for (var _e = 0, _f = Object.keys(rest); _e < _f.length; _e++) {
721
+ var k = _f[_e];
722
+ // Skip special request keys if any slipped through
723
+ if (specialKeys.has(k))
724
+ continue;
725
+ var shortKey = resolveShortKey(k);
726
+ if (pkShorts.includes(shortKey))
727
+ continue; // don't update PK columns (short or fully qualified)
728
+ updateBody[shortKey] = rest[k];
729
+ }
730
+ if (Object.keys(updateBody).length === 0) {
731
+ throw new Error("Singular PUT request for table (".concat(restModel.TABLE_NAME, ") must include at least one non-primary field to update."));
732
+ }
733
+ var normalized = (_b = {},
734
+ _b[C6Constants.UPDATE] = updateBody,
735
+ _b.WHERE = __assign({}, pkValues),
736
+ _b);
737
+ return __assign(__assign({}, normalized), { dataInsertMultipleRows: dataInsertMultipleRows, cacheResults: cacheResults, fetchDependencies: fetchDependencies, debug: debug, success: success, error: error });
738
+ }
739
+
623
740
  var HttpExecutor = /** @class */ (function (_super) {
624
741
  __extends(HttpExecutor, _super);
625
742
  function HttpExecutor() {
@@ -681,7 +798,6 @@ var HttpExecutor = /** @class */ (function (_super) {
681
798
  switch (_b.label) {
682
799
  case 0:
683
800
  _a = this.config, C6 = _a.C6, axios = _a.axios, restURL = _a.restURL, withCredentials = _a.withCredentials, restModel = _a.restModel, reactBootstrap = _a.reactBootstrap, requestMethod = _a.requestMethod, skipPrimaryCheck = _a.skipPrimaryCheck, clearCache = _a.clearCache;
684
- console.log('this.config', this.config);
685
801
  return [4 /*yield*/, this.runLifecycleHooks("beforeProcessing", {
686
802
  config: this.config,
687
803
  request: this.request,
@@ -727,7 +843,7 @@ var HttpExecutor = /** @class */ (function (_super) {
727
843
  query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
728
844
  }
729
845
  apiRequest = function () { return __awaiter(_this, void 0, void 0, function () {
730
- 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;
846
+ var _a, debug, _b, cacheResults, dataInsertMultipleRows, success, _c, fetchDependencies, _d, error, querySerialized, cacheResult, cachingConfirmed, cacheCheck, cacheCheck, addBackPK, removedPrimaryKV, apiResponse, returnGetNextPageFunction, restRequestUri, needsConditionOrPrimaryCheck, TABLES, primaryKey, removedPkValue_1, axiosActiveRequest;
731
847
  var _e;
732
848
  var _this = this;
733
849
  var _f, _g, _h, _j, _k, _l;
@@ -847,6 +963,7 @@ var HttpExecutor = /** @class */ (function (_super) {
847
963
  && primaryKey in query) {
848
964
  restRequestUri += query[primaryKey] + '/';
849
965
  removedPkValue_1 = query[primaryKey];
966
+ removedPrimaryKV = { key: primaryKey, value: removedPkValue_1 };
850
967
  addBackPK = function () {
851
968
  query !== null && query !== void 0 ? query : (query = {});
852
969
  query[primaryKey] = removedPkValue_1;
@@ -875,8 +992,8 @@ var HttpExecutor = /** @class */ (function (_super) {
875
992
  var baseConfig = {
876
993
  withCredentials: withCredentials,
877
994
  };
878
- // Pass-through request; singular normalization occurs on the backend (SqlExecutor)
879
- var normalizedQuery = query;
995
+ // Normalize singular request (GET/PUT/DELETE) into complex ORM shape
996
+ var normalizedQuery = normalizeSingularRequest(requestMethod, query, restModel, removedPrimaryKV);
880
997
  switch (requestMethod) {
881
998
  case GET:
882
999
  return [__assign(__assign({}, baseConfig), { params: normalizedQuery })];
@@ -1079,7 +1196,7 @@ var HttpExecutor = /** @class */ (function (_super) {
1079
1196
  accumulator.push(row['entity_tag']);
1080
1197
  }
1081
1198
  return accumulator;
1082
- }, []).map(function (entityTag) { return entityTag.split('\\').pop().toLowerCase(); });
1199
+ }, []).map(function (entityTag) { var _a, _b; return (_b = (_a = entityTag.split('\\')) === null || _a === void 0 ? void 0 : _a.pop()) === null || _b === void 0 ? void 0 : _b.toLowerCase(); });
1083
1200
  var shouldContinue = referencesTables.find(function (referencesTable) { return tableToFetch.endsWith(referencesTable); });
1084
1201
  if (!shouldContinue) {
1085
1202
  console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables);
@@ -1762,122 +1879,6 @@ var UpdateQueryBuilder = /** @class */ (function (_super) {
1762
1879
  return UpdateQueryBuilder;
1763
1880
  }(PaginationBuilder));
1764
1881
 
1765
- /**
1766
- * Converts a singular T-shaped request into complex ORM format for GET/PUT/DELETE
1767
- * Enforces that all primary keys are present for singular syntax and that the table has PKs.
1768
- * Optionally accepts a previously removed primary key (key/value) to reconstruct WHERE.
1769
- */
1770
- function normalizeSingularRequest(requestMethod, request, restModel, removedPrimary) {
1771
- var _a, _b;
1772
- var _c;
1773
- if (request == null || typeof request !== 'object')
1774
- return request;
1775
- var specialKeys = new Set([
1776
- C6Constants.SELECT,
1777
- C6Constants.UPDATE,
1778
- C6Constants.DELETE,
1779
- C6Constants.WHERE,
1780
- C6Constants.JOIN,
1781
- C6Constants.PAGINATION,
1782
- ]);
1783
- // Determine if the request is already complex (has any special key besides PAGINATION)
1784
- var keys = Object.keys(request);
1785
- var hasComplexKeys = keys.some(function (k) { return k !== C6Constants.PAGINATION && specialKeys.has(k); });
1786
- if (hasComplexKeys)
1787
- return request; // already complex
1788
- // We treat it as singular when it's not complex.
1789
- // For GET, PUT, DELETE only
1790
- if (!(requestMethod === C6Constants.GET || requestMethod === C6Constants.PUT || requestMethod === C6Constants.DELETE)) {
1791
- return request;
1792
- }
1793
- var pkShorts = Array.isArray(restModel.PRIMARY_SHORT) ? __spreadArray([], restModel.PRIMARY_SHORT, true) : [];
1794
- var pkFulls = Array.isArray(restModel.PRIMARY) ? __spreadArray([], restModel.PRIMARY, true) : [];
1795
- var resolveShortKey = function (key) {
1796
- var _a;
1797
- var cols = restModel.COLUMNS || {};
1798
- return (_a = cols[key]) !== null && _a !== void 0 ? _a : key;
1799
- };
1800
- if (!pkShorts.length) {
1801
- // For GET requests, do not enforce primary key presence; treat as a collection query.
1802
- if (requestMethod === C6Constants.GET)
1803
- return request;
1804
- throw new Error("Table (".concat(restModel.TABLE_NAME, ") has no primary key; singular request syntax is not allowed."));
1805
- }
1806
- // Build pk map from request + possibly removed primary key (accept short or fully-qualified keys)
1807
- var pkValues = {};
1808
- var requestObj = request;
1809
- var _loop_1 = function (pkShort) {
1810
- // 1) direct short key
1811
- var value = requestObj[pkShort];
1812
- if (value === undefined) {
1813
- // 2) fully-qualified key matching this short key (from PRIMARY list or by concatenation)
1814
- var fqCandidate_1 = "".concat(restModel.TABLE_NAME, ".").concat(pkShort);
1815
- var fqKey = (_c = pkFulls.find(function (fq) { return fq === fqCandidate_1 || fq.endsWith(".".concat(pkShort)); })) !== null && _c !== void 0 ? _c : fqCandidate_1;
1816
- value = requestObj[fqKey];
1817
- }
1818
- if (value === undefined && removedPrimary) {
1819
- // 3) removedPrimary may provide either short or fully-qualified key
1820
- var removedKeyShort = resolveShortKey(removedPrimary.key);
1821
- if (removedKeyShort === pkShort)
1822
- value = removedPrimary.value;
1823
- }
1824
- if (value !== undefined && value !== null) {
1825
- pkValues[pkShort] = value;
1826
- }
1827
- };
1828
- for (var _i = 0, pkShorts_1 = pkShorts; _i < pkShorts_1.length; _i++) {
1829
- var pkShort = pkShorts_1[_i];
1830
- _loop_1(pkShort);
1831
- }
1832
- var missing = pkShorts.filter(function (pk) { return !(pk in pkValues); });
1833
- if (missing.length) {
1834
- // For GET requests, if not all PKs are provided, treat as a collection query and leave as-is.
1835
- if (requestMethod === C6Constants.GET) {
1836
- return request;
1837
- }
1838
- throw new Error("Singular request requires all primary key(s) [".concat(pkShorts.join(', '), "] for table (").concat(restModel.TABLE_NAME, "). Missing: [").concat(missing.join(', '), "]"));
1839
- }
1840
- // Strip API metadata that should remain at root
1841
- var _d = request, dataInsertMultipleRows = _d.dataInsertMultipleRows, cacheResults = _d.cacheResults, fetchDependencies = _d.fetchDependencies, debug = _d.debug, success = _d.success, error = _d.error, rest = __rest(_d, ["dataInsertMultipleRows", "cacheResults", "fetchDependencies", "debug", "success", "error"]);
1842
- if (requestMethod === C6Constants.GET) {
1843
- var normalized_1 = {
1844
- WHERE: __assign({}, pkValues),
1845
- };
1846
- // Preserve pagination if any was added previously
1847
- if (request[C6Constants.PAGINATION]) {
1848
- normalized_1[C6Constants.PAGINATION] = request[C6Constants.PAGINATION];
1849
- }
1850
- return __assign(__assign({}, normalized_1), { dataInsertMultipleRows: dataInsertMultipleRows, cacheResults: cacheResults, fetchDependencies: fetchDependencies, debug: debug, success: success, error: error });
1851
- }
1852
- if (requestMethod === C6Constants.DELETE) {
1853
- var normalized_2 = (_a = {},
1854
- _a[C6Constants.DELETE] = true,
1855
- _a.WHERE = __assign({}, pkValues),
1856
- _a);
1857
- return __assign(__assign({}, normalized_2), { dataInsertMultipleRows: dataInsertMultipleRows, cacheResults: cacheResults, fetchDependencies: fetchDependencies, debug: debug, success: success, error: error });
1858
- }
1859
- // PUT
1860
- var updateBody = {};
1861
- for (var _e = 0, _f = Object.keys(rest); _e < _f.length; _e++) {
1862
- var k = _f[_e];
1863
- // Skip special request keys if any slipped through
1864
- if (specialKeys.has(k))
1865
- continue;
1866
- var shortKey = resolveShortKey(k);
1867
- if (pkShorts.includes(shortKey))
1868
- continue; // don't update PK columns (short or fully qualified)
1869
- updateBody[shortKey] = rest[k];
1870
- }
1871
- if (Object.keys(updateBody).length === 0) {
1872
- throw new Error("Singular PUT request for table (".concat(restModel.TABLE_NAME, ") must include at least one non-primary field to update."));
1873
- }
1874
- var normalized = (_b = {},
1875
- _b[C6Constants.UPDATE] = updateBody,
1876
- _b.WHERE = __assign({}, pkValues),
1877
- _b);
1878
- return __assign(__assign({}, normalized), { dataInsertMultipleRows: dataInsertMultipleRows, cacheResults: cacheResults, fetchDependencies: fetchDependencies, debug: debug, success: success, error: error });
1879
- }
1880
-
1881
1882
  var SqlExecutor = /** @class */ (function (_super) {
1882
1883
  __extends(SqlExecutor, _super);
1883
1884
  function SqlExecutor() {
@@ -2136,6 +2137,16 @@ function ExpressHandler(_a) {
2136
2137
  }); };
2137
2138
  }
2138
2139
 
2140
+ function createTestServer(_a) {
2141
+ var C6 = _a.C6, mysqlPool = _a.mysqlPool;
2142
+ var app = express();
2143
+ app.set('query parser', 'extended');
2144
+ app.use(express.json());
2145
+ app.all("/rest/:table", ExpressHandler({ C6: C6, mysqlPool: mysqlPool }));
2146
+ app.all("/rest/:table/:primary", ExpressHandler({ C6: C6, mysqlPool: mysqlPool }));
2147
+ return app;
2148
+ }
2149
+
2139
2150
  // Alias a table name with a given alias
2140
2151
  var A = function (tableName, alias) {
2141
2152
  return "".concat(tableName, " ").concat(alias);
@@ -2270,5 +2281,5 @@ function isVerbose () {
2270
2281
  return ['true', '1', 'yes', 'on'].includes(envVerbose.toLowerCase());
2271
2282
  }
2272
2283
 
2273
- export { A, AggregateBuilder, C6C, C6Constants, ConditionBuilder, DELETE, DeleteQueryBuilder, Executor, ExpressHandler, F, GET, HttpExecutor, JoinBuilder, POST, PUT, PaginationBuilder, PostQueryBuilder, SelectQueryBuilder, SqlExecutor, TestRestfulResponse, UpdateQueryBuilder, apiRequestCache, axiosInstance, bbox, checkAllRequestsComplete, checkCache, clearCache, convertForRequestBody, convertHexIfBinary, determineRuntimeJsType, distSphere, eFetchDependencies, error, fieldEq, getEnvVar, getPrimaryKeyTypes, group, info, isLocal, isNode, isTest, isVerbose, normalizeSingularRequest, onError, onSuccess, removeInvalidKeys, removePrefixIfExists, restOrm, restRequest, sortAndSerializeQueryObject, stContains, timeout, toastOptions, toastOptionsDevs, userCustomClearCache, warn };
2284
+ export { A, AggregateBuilder, C6C, C6Constants, ConditionBuilder, DELETE, DeleteQueryBuilder, Executor, ExpressHandler, F, GET, HttpExecutor, JoinBuilder, POST, PUT, PaginationBuilder, PostQueryBuilder, SelectQueryBuilder, SqlExecutor, TestRestfulResponse, UpdateQueryBuilder, apiRequestCache, axiosInstance, bbox, checkAllRequestsComplete, checkCache, clearCache, convertForRequestBody, convertHexIfBinary, createTestServer, determineRuntimeJsType, distSphere, eFetchDependencies, error, fieldEq, getEnvVar, getPrimaryKeyTypes, group, info, isLocal, isNode, isTest, isVerbose, normalizeSingularRequest, onError, onSuccess, removeInvalidKeys, removePrefixIfExists, restOrm, restRequest, sortAndSerializeQueryObject, stContains, timeout, toastOptions, toastOptionsDevs, userCustomClearCache, warn };
2274
2285
  //# sourceMappingURL=index.esm.js.map