@carbonorm/carbonnode 3.11.0 → 4.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.
- package/README.md +123 -493
- package/dist/api/orm/builders/ConditionBuilder.d.ts +5 -0
- package/dist/api/orm/queries/PostQueryBuilder.d.ts +1 -1
- package/dist/api/restOrm.d.ts +4 -4
- package/dist/api/types/ormInterfaces.d.ts +32 -12
- package/dist/api/utils/cacheManager.d.ts +7 -8
- package/dist/index.cjs.js +289 -140
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +285 -139
- package/dist/index.esm.js.map +1 -1
- package/package.json +1 -1
- package/src/__tests__/cacheManager.test.ts +67 -0
- package/src/__tests__/expressServer.e2e.test.ts +104 -2
- package/src/__tests__/fixtures/c6.fixture.ts +2 -0
- package/src/__tests__/httpExecutorSingular.e2e.test.ts +35 -4
- package/src/__tests__/sakila-db/C6.js +1 -1
- package/src/__tests__/sakila-db/C6.ts +1 -1
- package/src/__tests__/sqlBuilders.test.ts +45 -0
- package/src/api/axiosInstance.ts +29 -0
- package/src/api/executors/HttpExecutor.ts +73 -97
- package/src/api/handlers/ExpressHandler.ts +30 -7
- package/src/api/orm/builders/ConditionBuilder.ts +74 -0
- package/src/api/orm/queries/PostQueryBuilder.ts +4 -2
- package/src/api/orm/queries/UpdateQueryBuilder.ts +3 -1
- package/src/api/types/ormInterfaces.ts +32 -18
- package/src/api/utils/cacheManager.ts +75 -34
- package/src/api/utils/testHelpers.ts +5 -3
- package/src/variables/isNode.ts +1 -8
|
@@ -8,14 +8,13 @@ import {OrmGenerics} from "../types/ormGenerics";
|
|
|
8
8
|
import {
|
|
9
9
|
DELETE, DetermineResponseDataType,
|
|
10
10
|
GET,
|
|
11
|
-
iCacheAPI,
|
|
12
11
|
iConstraint,
|
|
13
|
-
|
|
12
|
+
C6RestResponse,
|
|
14
13
|
POST,
|
|
15
14
|
PUT, RequestQueryBody
|
|
16
15
|
} from "../types/ormInterfaces";
|
|
17
16
|
import {removeInvalidKeys, removePrefixIfExists, TestRestfulResponse} from "../utils/apiHelpers";
|
|
18
|
-
import {
|
|
17
|
+
import {checkCache, setCache, userCustomClearCache} from "../utils/cacheManager";
|
|
19
18
|
import {sortAndSerializeQueryObject} from "../utils/sortAndSerializeQueryObject";
|
|
20
19
|
import {Executor} from "./Executor";
|
|
21
20
|
import {toastOptions, toastOptionsDevs} from "variables/toastOptions";
|
|
@@ -27,8 +26,11 @@ export class HttpExecutor<
|
|
|
27
26
|
|
|
28
27
|
private isRestResponse<T extends Record<string, any>>(
|
|
29
28
|
r: AxiosResponse<any>
|
|
30
|
-
): r is AxiosResponse<
|
|
31
|
-
return !!r
|
|
29
|
+
): r is AxiosResponse<C6RestResponse<'GET', T>> {
|
|
30
|
+
return !!r
|
|
31
|
+
&& r.data != null
|
|
32
|
+
&& typeof r.data === 'object'
|
|
33
|
+
&& Array.isArray((r.data as C6RestResponse<'GET', T>).rest);
|
|
32
34
|
}
|
|
33
35
|
|
|
34
36
|
private stripTableNameFromKeys<T extends Record<string, any>>(obj: Partial<T> | undefined | null): Partial<T> {
|
|
@@ -182,20 +184,6 @@ export class HttpExecutor<
|
|
|
182
184
|
console.groupEnd()
|
|
183
185
|
}
|
|
184
186
|
|
|
185
|
-
// an undefined query would indicate queryCallback returned undefined,
|
|
186
|
-
// thus the request shouldn't fire as is in custom cache
|
|
187
|
-
if (undefined === this.request || null === this.request) {
|
|
188
|
-
|
|
189
|
-
if (isLocal()) {
|
|
190
|
-
console.groupCollapsed(`API: (${requestMethod}) (${tableName}) query undefined/null → returning null`)
|
|
191
|
-
console.log('request', this.request)
|
|
192
|
-
console.groupEnd()
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
return null;
|
|
196
|
-
|
|
197
|
-
}
|
|
198
|
-
|
|
199
187
|
let query = this.request;
|
|
200
188
|
|
|
201
189
|
// this is parameterless and could return itself with a new page number, or undefined if the end is reached
|
|
@@ -219,14 +207,6 @@ export class HttpExecutor<
|
|
|
219
207
|
console.groupEnd()
|
|
220
208
|
}
|
|
221
209
|
|
|
222
|
-
// The problem with creating cache keys with a stringified object is the order of keys matters and it's possible for the same query to be stringified differently.
|
|
223
|
-
// Here we ensure the key order will be identical between two of the same requests. https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key
|
|
224
|
-
|
|
225
|
-
// literally impossible for query to be undefined or null here but the editor is too busy licking windows to understand that
|
|
226
|
-
let querySerialized: string = sortAndSerializeQueryObject(tables, query ?? {});
|
|
227
|
-
|
|
228
|
-
let cacheResult: iCacheAPI | undefined = apiRequestCache.find(cache => cache.requestArgumentsSerialized === querySerialized);
|
|
229
|
-
|
|
230
210
|
let cachingConfirmed = false;
|
|
231
211
|
|
|
232
212
|
// determine if we need to paginate.
|
|
@@ -253,52 +233,42 @@ export class HttpExecutor<
|
|
|
253
233
|
|
|
254
234
|
query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
|
|
255
235
|
|
|
256
|
-
|
|
257
|
-
if (true === cacheResults) {
|
|
258
|
-
if (undefined !== cacheResult) {
|
|
259
|
-
do {
|
|
260
|
-
const cacheCheck = checkCache<ResponseDataType>(cacheResult, requestMethod, tableName, this.request);
|
|
261
|
-
if (false !== cacheCheck) {
|
|
262
|
-
return (await cacheCheck).data;
|
|
263
|
-
}
|
|
264
|
-
++query[C6.PAGINATION][C6.PAGE];
|
|
265
|
-
querySerialized = sortAndSerializeQueryObject(tables, query ?? {});
|
|
266
|
-
cacheResult = apiRequestCache.find(cache => cache.requestArgumentsSerialized === querySerialized)
|
|
267
|
-
} while (undefined !== cacheResult)
|
|
268
|
-
if (debug && isLocal()) {
|
|
269
|
-
toast.warning("DEVS: Request pages exhausted in cache; firing network.", toastOptionsDevs);
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
cachingConfirmed = true;
|
|
273
|
-
} else {
|
|
274
|
-
if (debug && isLocal()) toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
if (debug && isLocal()) {
|
|
278
|
-
toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? " Page (" + query[C6.PAGINATION][C6.PAGE] + ")" : ''), toastOptionsDevs);
|
|
279
|
-
}
|
|
236
|
+
}
|
|
280
237
|
|
|
281
|
-
|
|
238
|
+
// The problem with creating cache keys with a stringified object is the order of keys matters and it's possible for the same query to be stringified differently.
|
|
239
|
+
// Here we ensure the key order will be identical between two of the same requests. https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key
|
|
240
|
+
const cacheRequestData = JSON.parse(JSON.stringify(query ?? {})) as RequestQueryBody<
|
|
241
|
+
G['RequestMethod'],
|
|
242
|
+
G['RestTableInterface'],
|
|
243
|
+
G['CustomAndRequiredFields'],
|
|
244
|
+
G['RequestTableOverrides']
|
|
245
|
+
>;
|
|
282
246
|
|
|
283
|
-
|
|
284
|
-
|
|
247
|
+
// literally impossible for query to be undefined or null here but the editor is too busy licking windows to understand that
|
|
248
|
+
let querySerialized: string = sortAndSerializeQueryObject(tables, cacheRequestData ?? {});
|
|
285
249
|
|
|
286
|
-
|
|
250
|
+
let cachedRequest: AxiosPromise<ResponseDataType> | false = false;
|
|
287
251
|
|
|
288
|
-
|
|
252
|
+
if (cacheResults) {
|
|
253
|
+
cachedRequest = checkCache<ResponseDataType>(requestMethod, tableName, cacheRequestData);
|
|
254
|
+
}
|
|
289
255
|
|
|
290
|
-
|
|
291
|
-
|
|
256
|
+
if (cachedRequest) {
|
|
257
|
+
return (await cachedRequest).data;
|
|
258
|
+
}
|
|
292
259
|
|
|
260
|
+
if (cacheResults) {
|
|
293
261
|
cachingConfirmed = true;
|
|
294
|
-
|
|
262
|
+
} else if (debug && isLocal()) {
|
|
263
|
+
toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
|
|
264
|
+
}
|
|
295
265
|
|
|
266
|
+
if (cacheResults && debug && isLocal()) {
|
|
267
|
+
toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? " Page (" + query[C6.PAGINATION][C6.PAGE] + ")" : ''), toastOptionsDevs);
|
|
296
268
|
}
|
|
297
269
|
|
|
298
270
|
let apiResponse: G['RestTableInterface'][G['PrimaryKey']] | string | boolean | number | undefined;
|
|
299
271
|
|
|
300
|
-
let returnGetNextPageFunction = false;
|
|
301
|
-
|
|
302
272
|
let restRequestUri: string = restURL + operatingTable + '/';
|
|
303
273
|
|
|
304
274
|
const needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
|
|
@@ -460,22 +430,30 @@ export class HttpExecutor<
|
|
|
460
430
|
|
|
461
431
|
|
|
462
432
|
if (cachingConfirmed) {
|
|
463
|
-
|
|
464
|
-
// push to cache so we do not repeat the request
|
|
465
|
-
apiRequestCache.push({
|
|
433
|
+
setCache<ResponseDataType>(requestMethod, tableName, cacheRequestData, {
|
|
466
434
|
requestArgumentsSerialized: querySerialized,
|
|
467
|
-
request: axiosActiveRequest
|
|
435
|
+
request: axiosActiveRequest,
|
|
468
436
|
});
|
|
469
|
-
|
|
470
437
|
}
|
|
471
438
|
|
|
472
439
|
// returning the promise with this then is important for tests. todo - we could make that optional.
|
|
473
440
|
// https://rapidapi.com/guides/axios-async-await
|
|
474
441
|
return axiosActiveRequest.then(async (response: AxiosResponse<ResponseDataType, any>): Promise<AxiosResponse<ResponseDataType, any>> => {
|
|
475
442
|
|
|
443
|
+
let hasNext: boolean | undefined;
|
|
444
|
+
|
|
476
445
|
// noinspection SuspiciousTypeOfGuard
|
|
477
446
|
if (typeof response.data === 'string') {
|
|
478
447
|
|
|
448
|
+
if (cachingConfirmed) {
|
|
449
|
+
setCache<ResponseDataType>(requestMethod, tableName, cacheRequestData, {
|
|
450
|
+
requestArgumentsSerialized: querySerialized,
|
|
451
|
+
request: axiosActiveRequest,
|
|
452
|
+
response,
|
|
453
|
+
final: true,
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
|
|
479
457
|
if (isTest()) {
|
|
480
458
|
|
|
481
459
|
console.trace()
|
|
@@ -489,15 +467,11 @@ export class HttpExecutor<
|
|
|
489
467
|
}
|
|
490
468
|
|
|
491
469
|
if (cachingConfirmed) {
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
// only cache get method requests
|
|
499
|
-
apiRequestCache[cacheIndex].response = response
|
|
500
|
-
|
|
470
|
+
setCache<ResponseDataType>(requestMethod, tableName, cacheRequestData, {
|
|
471
|
+
requestArgumentsSerialized: querySerialized,
|
|
472
|
+
request: axiosActiveRequest,
|
|
473
|
+
response,
|
|
474
|
+
});
|
|
501
475
|
}
|
|
502
476
|
|
|
503
477
|
this.runLifecycleHooks<"afterExecution">(
|
|
@@ -549,27 +523,30 @@ export class HttpExecutor<
|
|
|
549
523
|
callback();
|
|
550
524
|
}
|
|
551
525
|
|
|
552
|
-
if (C6.GET === requestMethod && this.isRestResponse
|
|
526
|
+
if (C6.GET === requestMethod && this.isRestResponse(response)) {
|
|
553
527
|
|
|
554
528
|
const responseData = response.data;
|
|
555
529
|
|
|
556
530
|
const pageLimit = query?.[C6.PAGINATION]?.[C6.LIMIT];
|
|
531
|
+
|
|
557
532
|
const got = responseData.rest.length;
|
|
558
|
-
|
|
533
|
+
hasNext = pageLimit !== 1 && got === pageLimit;
|
|
559
534
|
|
|
560
535
|
if (hasNext) {
|
|
561
|
-
responseData.next = apiRequest
|
|
536
|
+
responseData.next = apiRequest as () => Promise<
|
|
537
|
+
DetermineResponseDataType<'GET', G['RestTableInterface']>
|
|
538
|
+
>;
|
|
562
539
|
} else {
|
|
563
540
|
responseData.next = undefined; // short page => done
|
|
564
541
|
}
|
|
565
542
|
|
|
566
|
-
// If you keep this flag, make it reflect reality:
|
|
567
|
-
returnGetNextPageFunction = hasNext;
|
|
568
|
-
|
|
569
|
-
// and fix cache ‘final’ flag to match:
|
|
570
543
|
if (cachingConfirmed) {
|
|
571
|
-
|
|
572
|
-
|
|
544
|
+
setCache<ResponseDataType>(requestMethod, tableName, cacheRequestData, {
|
|
545
|
+
requestArgumentsSerialized: querySerialized,
|
|
546
|
+
request: axiosActiveRequest,
|
|
547
|
+
response,
|
|
548
|
+
final: !hasNext,
|
|
549
|
+
});
|
|
573
550
|
}
|
|
574
551
|
|
|
575
552
|
if ((this.config.verbose || debug) && isLocal()) {
|
|
@@ -580,11 +557,9 @@ export class HttpExecutor<
|
|
|
580
557
|
}
|
|
581
558
|
|
|
582
559
|
// next already set above based on hasNext; avoid duplicate, inverted logic
|
|
583
|
-
|
|
584
|
-
|
|
585
560
|
if (fetchDependencies
|
|
586
561
|
&& 'number' === typeof fetchDependencies
|
|
587
|
-
&& responseData.rest
|
|
562
|
+
&& responseData.rest?.length > 0) {
|
|
588
563
|
|
|
589
564
|
console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
|
|
590
565
|
+ (fetchDependencies & eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
|
|
@@ -827,6 +802,15 @@ export class HttpExecutor<
|
|
|
827
802
|
|
|
828
803
|
}
|
|
829
804
|
|
|
805
|
+
if (cachingConfirmed && hasNext === undefined) {
|
|
806
|
+
setCache<ResponseDataType>(requestMethod, tableName, cacheRequestData, {
|
|
807
|
+
requestArgumentsSerialized: querySerialized,
|
|
808
|
+
request: axiosActiveRequest,
|
|
809
|
+
response,
|
|
810
|
+
final: true,
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
|
|
830
814
|
if (debug && isLocal()) {
|
|
831
815
|
|
|
832
816
|
toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
|
|
@@ -841,25 +825,17 @@ export class HttpExecutor<
|
|
|
841
825
|
|
|
842
826
|
} catch (throwableError) {
|
|
843
827
|
|
|
844
|
-
if (isTest()) {
|
|
845
|
-
|
|
846
|
-
throw new Error(JSON.stringify(throwableError))
|
|
847
|
-
|
|
848
|
-
}
|
|
849
|
-
|
|
850
828
|
console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000')
|
|
851
829
|
|
|
852
830
|
console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0')
|
|
853
831
|
|
|
854
|
-
console.
|
|
832
|
+
console.error(throwableError)
|
|
855
833
|
|
|
856
834
|
console.trace()
|
|
857
835
|
|
|
858
836
|
console.groupEnd()
|
|
859
837
|
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
return null;
|
|
838
|
+
throw new Error(JSON.stringify(throwableError))
|
|
863
839
|
|
|
864
840
|
}
|
|
865
841
|
|
|
@@ -13,7 +13,7 @@ export function ExpressHandler({C6, mysqlPool}: { C6: iC6Object, mysqlPool: Pool
|
|
|
13
13
|
try {
|
|
14
14
|
const incomingMethod = req.method.toUpperCase() as iRestMethods;
|
|
15
15
|
const table = req.params.table;
|
|
16
|
-
|
|
16
|
+
let primary = req.params.primary;
|
|
17
17
|
// Support Axios interceptor promoting large GETs to POST with ?METHOD=GET
|
|
18
18
|
const methodOverrideRaw = (req.query?.METHOD ?? req.query?.method) as unknown;
|
|
19
19
|
const methodOverride = typeof methodOverrideRaw === 'string' ? methodOverrideRaw.toUpperCase() : undefined;
|
|
@@ -38,17 +38,40 @@ export function ExpressHandler({C6, mysqlPool}: { C6: iC6Object, mysqlPool: Pool
|
|
|
38
38
|
return;
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
-
const
|
|
41
|
+
const restModel = C6.TABLES[table];
|
|
42
|
+
const primaryKeys = restModel.PRIMARY;
|
|
43
|
+
const primaryShortKeys = restModel.PRIMARY_SHORT ?? [];
|
|
44
|
+
const columnMap = restModel.COLUMNS ?? {};
|
|
45
|
+
const resolveShortKey = (fullKey: string, index: number) =>
|
|
46
|
+
(columnMap as any)[fullKey] ?? primaryShortKeys[index] ?? fullKey.split('.').pop() ?? fullKey;
|
|
47
|
+
const hasPrimaryKeyValues = (data: any) => {
|
|
48
|
+
if (!data || typeof data !== 'object') return false;
|
|
49
|
+
const whereClause = (data as any)[C6C.WHERE];
|
|
50
|
+
const hasKeyValue = (obj: any, fullKey: string, shortKey: string) => {
|
|
51
|
+
if (!obj || typeof obj !== 'object') return false;
|
|
52
|
+
const fullValue = obj[fullKey];
|
|
53
|
+
if (fullValue !== undefined && fullValue !== null) return true;
|
|
54
|
+
const shortValue = shortKey ? obj[shortKey] : undefined;
|
|
55
|
+
return shortValue !== undefined && shortValue !== null;
|
|
56
|
+
};
|
|
57
|
+
return primaryKeys.every((fullKey, index) => {
|
|
58
|
+
const shortKey = resolveShortKey(fullKey, index);
|
|
59
|
+
return hasKeyValue(whereClause, fullKey, shortKey) || hasKeyValue(data, fullKey, shortKey);
|
|
60
|
+
});
|
|
61
|
+
};
|
|
42
62
|
|
|
43
63
|
if (primary && primaryKeys.length !== 1) {
|
|
44
|
-
if (primaryKeys.length > 1) {
|
|
64
|
+
if (primaryKeys.length > 1 && hasPrimaryKeyValues(payload)) {
|
|
65
|
+
primary = undefined;
|
|
66
|
+
} else if (primaryKeys.length > 1) {
|
|
45
67
|
res.status(400).json({error: `Table ${table} has multiple primary keys. Cannot implicitly determine key.`});
|
|
46
68
|
return;
|
|
69
|
+
} else {
|
|
70
|
+
res.status(400).json({
|
|
71
|
+
error: `Table ${table} has no primary keys. Please specify one.`
|
|
72
|
+
});
|
|
73
|
+
return;
|
|
47
74
|
}
|
|
48
|
-
res.status(400).json({
|
|
49
|
-
error: `Table ${table} has no primary keys. Please specify one.`
|
|
50
|
-
});
|
|
51
|
-
return;
|
|
52
75
|
}
|
|
53
76
|
|
|
54
77
|
const primaryKeyName = primaryKeys[0];
|
|
@@ -378,6 +378,80 @@ export abstract class ConditionBuilder<
|
|
|
378
378
|
throw new Error('Unsupported operand type in SQL expression.');
|
|
379
379
|
}
|
|
380
380
|
|
|
381
|
+
private isPlainArrayLiteral(value: any, allowColumnRefs = false): boolean {
|
|
382
|
+
if (!Array.isArray(value)) return false;
|
|
383
|
+
return value.every(item => {
|
|
384
|
+
if (item === null) return true;
|
|
385
|
+
const type = typeof item;
|
|
386
|
+
if (type === 'string' || type === 'number' || type === 'boolean') return true;
|
|
387
|
+
if (Array.isArray(item)) return this.isPlainArrayLiteral(item, allowColumnRefs);
|
|
388
|
+
if (item && typeof item === 'object') return this.isPlainObjectLiteral(item, allowColumnRefs);
|
|
389
|
+
return false;
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
private isPlainObjectLiteral(value: any, allowColumnRefs = false): boolean {
|
|
394
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
395
|
+
if (value instanceof Date) return false;
|
|
396
|
+
if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(value)) return false;
|
|
397
|
+
|
|
398
|
+
const normalized = value instanceof Map ? Object.fromEntries(value) : value;
|
|
399
|
+
if (C6C.SUBSELECT in (normalized as any)) return false;
|
|
400
|
+
|
|
401
|
+
const entries = Object.entries(normalized as Record<string, any>);
|
|
402
|
+
if (entries.length === 0) return true;
|
|
403
|
+
|
|
404
|
+
if (entries.some(([key]) => this.isOperator(key) || this.BOOLEAN_OPERATORS.has(key))) {
|
|
405
|
+
return false;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
if (!allowColumnRefs) {
|
|
409
|
+
if (entries.some(([key]) => typeof key === 'string' && (this.isColumnRef(key) || key.includes('.')))) {
|
|
410
|
+
return false;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
return true;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
private resolveColumnDefinition(column?: string): any | undefined {
|
|
418
|
+
if (!column || typeof column !== 'string' || !column.includes('.')) return undefined;
|
|
419
|
+
const [prefix, colName] = column.split('.', 2);
|
|
420
|
+
const tableName = this.aliasMap[prefix] ?? prefix;
|
|
421
|
+
const table = this.config.C6?.TABLES?.[tableName];
|
|
422
|
+
if (!table?.TYPE_VALIDATION) return undefined;
|
|
423
|
+
return table.TYPE_VALIDATION[colName] ?? table.TYPE_VALIDATION[`${tableName}.${colName}`];
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
private isJsonColumn(column?: string): boolean {
|
|
427
|
+
const columnDef = this.resolveColumnDefinition(column);
|
|
428
|
+
const mysqlType = columnDef?.MYSQL_TYPE;
|
|
429
|
+
return typeof mysqlType === 'string' && mysqlType.toLowerCase().includes('json');
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
protected serializeUpdateValue(
|
|
433
|
+
value: any,
|
|
434
|
+
params: any[] | Record<string, any>,
|
|
435
|
+
contextColumn?: string
|
|
436
|
+
): string {
|
|
437
|
+
const normalized = value instanceof Map ? Object.fromEntries(value) : value;
|
|
438
|
+
|
|
439
|
+
const allowColumnRefs = this.isJsonColumn(contextColumn);
|
|
440
|
+
|
|
441
|
+
if (this.isPlainArrayLiteral(normalized, allowColumnRefs)
|
|
442
|
+
|| this.isPlainObjectLiteral(normalized, allowColumnRefs)) {
|
|
443
|
+
return this.addParam(params, contextColumn ?? '', JSON.stringify(normalized));
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
const { sql, isReference, isExpression, isSubSelect } = this.serializeOperand(normalized, params, contextColumn);
|
|
447
|
+
|
|
448
|
+
if (!isReference && !isExpression && !isSubSelect && typeof normalized === 'object' && normalized !== null) {
|
|
449
|
+
throw new Error('Unsupported operand type in SQL expression.');
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
return sql;
|
|
453
|
+
}
|
|
454
|
+
|
|
381
455
|
private ensurePlainObject<T>(value: T): any {
|
|
382
456
|
if (value instanceof Map) {
|
|
383
457
|
return Object.fromEntries(value as unknown as Map<string, any>);
|
|
@@ -18,13 +18,15 @@ export class PostQueryBuilder<G extends OrmGenerics> extends ConditionBuilder<G>
|
|
|
18
18
|
const verb = C6C.REPLACE in this.request ? C6C.REPLACE : C6C.INSERT;
|
|
19
19
|
const body = verb in this.request ? this.request[verb] : this.request;
|
|
20
20
|
const keys = Object.keys(body);
|
|
21
|
-
const params: any[] = []
|
|
21
|
+
const params: any[] | Record<string, any> = this.useNamedParams ? {} : [];
|
|
22
22
|
const placeholders: string[] = []
|
|
23
23
|
|
|
24
24
|
|
|
25
25
|
for (const key of keys) {
|
|
26
26
|
const value = body[key];
|
|
27
|
-
const
|
|
27
|
+
const trimmed = this.trimTablePrefix(table, key);
|
|
28
|
+
const qualified = `${table}.${trimmed}`;
|
|
29
|
+
const placeholder = this.serializeUpdateValue(value, params, qualified);
|
|
28
30
|
placeholders.push(placeholder);
|
|
29
31
|
}
|
|
30
32
|
|
|
@@ -39,7 +39,9 @@ export class UpdateQueryBuilder<G extends OrmGenerics> extends PaginationBuilder
|
|
|
39
39
|
.map(([col, val]) => {
|
|
40
40
|
const trimmed = this.trimTablePrefix(table, col);
|
|
41
41
|
const qualified = `${table}.${trimmed}`;
|
|
42
|
-
|
|
42
|
+
this.assertValidIdentifier(qualified, 'UPDATE SET');
|
|
43
|
+
const rightSql = this.serializeUpdateValue(val, params, qualified);
|
|
44
|
+
return `\`${trimmed}\` = ${rightSql}`;
|
|
43
45
|
});
|
|
44
46
|
|
|
45
47
|
sql += ` SET ${setClauses.join(', ')}`;
|
|
@@ -97,7 +97,13 @@ export type RequestQueryBody<
|
|
|
97
97
|
export interface iCacheAPI<ResponseDataType = any> {
|
|
98
98
|
requestArgumentsSerialized: string;
|
|
99
99
|
request: AxiosPromise<ResponseDataType>;
|
|
100
|
-
response?: AxiosResponse
|
|
100
|
+
response?: AxiosResponse & {
|
|
101
|
+
__carbonTiming?: {
|
|
102
|
+
start: number;
|
|
103
|
+
end: number;
|
|
104
|
+
duration: number;
|
|
105
|
+
}
|
|
106
|
+
},
|
|
101
107
|
final?: boolean;
|
|
102
108
|
}
|
|
103
109
|
|
|
@@ -105,40 +111,48 @@ export interface iChangeC6Data {
|
|
|
105
111
|
rowCount: number;
|
|
106
112
|
}
|
|
107
113
|
|
|
108
|
-
|
|
114
|
+
// New discriminated REST response type based on HTTP method
|
|
115
|
+
export type C6RestResponse<
|
|
116
|
+
Method extends iRestMethods,
|
|
117
|
+
RestData extends { [key: string]: any },
|
|
118
|
+
Overrides = {}
|
|
119
|
+
> = {
|
|
120
|
+
rest: Method extends 'GET' ? Modify<RestData, Overrides>[] : Modify<RestData, Overrides>;
|
|
121
|
+
session?: any;
|
|
122
|
+
sql?: any;
|
|
123
|
+
} & (Method extends 'GET'
|
|
124
|
+
? { next?: () => Promise<DetermineResponseDataType<'GET', RestData, Overrides>> }
|
|
125
|
+
: {});
|
|
126
|
+
|
|
127
|
+
export interface iC6RestResponse<RestData> {
|
|
128
|
+
// Backwards compatibility: base interface for rest/sql/session (singular)
|
|
129
|
+
rest: RestData;
|
|
130
|
+
session?: any;
|
|
131
|
+
sql?: any;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export interface iDeleteC6RestResponse<RestData extends { [key: string]: any; }, RequestData = any> extends iChangeC6Data, C6RestResponse<'DELETE', RestData> {
|
|
109
135
|
deleted: boolean | number | string | RequestData;
|
|
110
136
|
}
|
|
111
137
|
|
|
112
|
-
export interface iPostC6RestResponse<RestData
|
|
138
|
+
export interface iPostC6RestResponse<RestData extends { [key: string]: any; }> extends C6RestResponse<'POST', RestData> {
|
|
113
139
|
created: boolean | number | string;
|
|
114
140
|
}
|
|
115
141
|
|
|
116
|
-
export interface iPutC6RestResponse<RestData
|
|
142
|
+
export interface iPutC6RestResponse<RestData extends { [key: string]: any; }, RequestData = any> extends iChangeC6Data, C6RestResponse<'PUT', RestData> {
|
|
117
143
|
updated: boolean | number | string | RequestData;
|
|
118
144
|
}
|
|
119
145
|
|
|
120
|
-
export interface iC6RestResponse<RestData> {
|
|
121
|
-
rest: RestData;
|
|
122
|
-
session?: any;
|
|
123
|
-
sql?: any;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
146
|
export interface iGetC6RestResponse<
|
|
127
147
|
ResponseDataType extends { [key: string]: any },
|
|
128
148
|
ResponseDataOverrides = {}
|
|
129
|
-
> extends
|
|
130
|
-
// TODO - We removed Modify<ResponseDataType, ResponseDataOverrides> |
|
|
131
|
-
Modify<ResponseDataType, ResponseDataOverrides>[]
|
|
132
|
-
> {
|
|
133
|
-
next?: () => Promise<DetermineResponseDataType<"GET", ResponseDataType, ResponseDataOverrides>>;
|
|
134
|
-
}
|
|
149
|
+
> extends C6RestResponse<'GET', ResponseDataType, ResponseDataOverrides> {}
|
|
135
150
|
|
|
136
151
|
export type DetermineResponseDataType<
|
|
137
152
|
Method extends iRestMethods,
|
|
138
153
|
RestTableInterface extends { [key: string]: any },
|
|
139
154
|
ResponseDataOverrides = {}
|
|
140
|
-
> =
|
|
141
|
-
(Method extends 'POST'
|
|
155
|
+
> = (Method extends 'POST'
|
|
142
156
|
? iPostC6RestResponse<RestTableInterface>
|
|
143
157
|
: Method extends 'GET'
|
|
144
158
|
? iGetC6RestResponse<RestTableInterface, ResponseDataOverrides>
|