@carbonorm/carbonnode 3.0.0 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/api/builders/sqlBuilder.d.ts +3 -0
  2. package/dist/api/convertForRequestBody.d.ts +1 -1
  3. package/dist/api/executors/Executor.d.ts +16 -0
  4. package/dist/api/executors/HttpExecutor.d.ts +13 -0
  5. package/dist/api/executors/SqlExecutor.d.ts +19 -0
  6. package/dist/api/restRequest.d.ts +9 -166
  7. package/dist/api/types/dynamicFetching.d.ts +10 -0
  8. package/dist/api/types/modifyTypes.d.ts +9 -0
  9. package/dist/api/types/mysqlTypes.d.ts +4 -0
  10. package/dist/api/types/ormInterfaces.d.ts +219 -0
  11. package/dist/api/utils/apiHelpers.d.ts +9 -0
  12. package/dist/api/utils/cacheManager.d.ts +10 -0
  13. package/dist/api/utils/determineRuntimeJsType.d.ts +5 -0
  14. package/dist/api/utils/logger.d.ts +7 -0
  15. package/dist/api/utils/sortAndSerializeQueryObject.d.ts +1 -0
  16. package/dist/api/utils/testHelpers.d.ts +1 -0
  17. package/dist/api/utils/toastNotifier.d.ts +2 -0
  18. package/dist/index.cjs.js +665 -614
  19. package/dist/index.cjs.js.map +1 -1
  20. package/dist/index.d.ts +15 -2
  21. package/dist/index.esm.js +655 -618
  22. package/dist/index.esm.js.map +1 -1
  23. package/package.json +22 -6
  24. package/scripts/assets/handlebars/C6.ts.handlebars +13 -5
  25. package/scripts/assets/handlebars/Table.ts.handlebars +44 -12
  26. package/scripts/generateRestBindings.cjs +1 -1
  27. package/scripts/generateRestBindings.ts +1 -1
  28. package/src/api/builders/sqlBuilder.ts +173 -0
  29. package/src/api/convertForRequestBody.ts +2 -3
  30. package/src/api/executors/Executor.ts +28 -0
  31. package/src/api/executors/HttpExecutor.ts +794 -0
  32. package/src/api/executors/SqlExecutor.ts +104 -0
  33. package/src/api/restRequest.ts +50 -1287
  34. package/src/api/types/dynamicFetching.ts +10 -0
  35. package/src/api/types/modifyTypes.ts +25 -0
  36. package/src/api/types/mysqlTypes.ts +33 -0
  37. package/src/api/types/ormInterfaces.ts +310 -0
  38. package/src/api/utils/apiHelpers.ts +82 -0
  39. package/src/api/utils/cacheManager.ts +67 -0
  40. package/src/api/utils/determineRuntimeJsType.ts +46 -0
  41. package/src/api/utils/logger.ts +24 -0
  42. package/src/api/utils/sortAndSerializeQueryObject.ts +12 -0
  43. package/src/api/utils/testHelpers.ts +24 -0
  44. package/src/api/utils/toastNotifier.ts +11 -0
  45. package/src/index.ts +15 -2
  46. package/src/api/carbonSqlExecutor.ts +0 -279
  47. package/src/api/interfaces/ormInterfaces.ts +0 -87
@@ -0,0 +1,794 @@
1
+ import {AxiosPromise, AxiosResponse} from "axios";
2
+ import {toast} from "react-toastify";
3
+ import isLocal from "../../variables/isLocal";
4
+ import isTest from "../../variables/isTest";
5
+ import isVerbose from "../../variables/isVerbose";
6
+ import convertForRequestBody from "../convertForRequestBody";
7
+ import {eFetchDependencies} from "../types/dynamicFetching";
8
+ import {Modify} from "../types/modifyTypes";
9
+ import {apiReturn, DELETE, GET, iCacheAPI, iConstraint, iGetC6RestResponse, POST, PUT, RequestQueryBody} from "../types/ormInterfaces";
10
+ import {removePrefixIfExists, TestRestfulResponse} from "../utils/apiHelpers";
11
+ import {apiRequestCache, checkCache, userCustomClearCache} from "../utils/cacheManager";
12
+ import {sortAndSerializeQueryObject} from "../utils/sortAndSerializeQueryObject";
13
+ import {Executor} from "./Executor";
14
+ import {toastOptions, toastOptionsDevs } from "variables/toastOptions";
15
+
16
+ export class HttpExecutor<
17
+ RestShortTableName extends string = any,
18
+ RestTableInterface extends { [key: string]: any } = any,
19
+ PrimaryKey extends Extract<keyof RestTableInterface, string> = Extract<keyof RestTableInterface, string>,
20
+ CustomAndRequiredFields extends { [key: string]: any } = any,
21
+ RequestTableOverrides extends { [key: string]: any; } = { [key in keyof RestTableInterface]: any },
22
+ ResponseDataType = any
23
+ >
24
+ extends Executor<
25
+ RestShortTableName,
26
+ RestTableInterface,
27
+ PrimaryKey,
28
+ CustomAndRequiredFields,
29
+ RequestTableOverrides,
30
+ ResponseDataType
31
+ > {
32
+
33
+ public async execute() : Promise<apiReturn<ResponseDataType>> {
34
+
35
+ const {
36
+ C6,
37
+ axios,
38
+ restURL,
39
+ withCredentials,
40
+ restModel,
41
+ requestMethod,
42
+ queryCallback,
43
+ responseCallback,
44
+ skipPrimaryCheck,
45
+ clearCache,
46
+ } = this.config
47
+
48
+ const tableName = restModel.TABLE_NAME;
49
+
50
+ const fullTableList = Array.isArray(tableName) ? tableName : [tableName];
51
+
52
+ const operatingTableFullName = fullTableList[0];
53
+
54
+ const operatingTable = removePrefixIfExists(operatingTableFullName, C6.PREFIX);
55
+
56
+ const tables = fullTableList.join(',')
57
+
58
+ switch (requestMethod) {
59
+ case GET:
60
+ case POST:
61
+ case PUT:
62
+ case DELETE:
63
+ break;
64
+ default:
65
+ throw Error('Bad request method passed to getApi')
66
+ }
67
+
68
+ if (null !== clearCache || undefined !== clearCache) {
69
+
70
+ userCustomClearCache[tables + requestMethod] = clearCache;
71
+
72
+ }
73
+
74
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request for (' + tableName + ')', 'color: #0c0')
75
+
76
+ console.log('request', this.request)
77
+
78
+ console.groupEnd()
79
+
80
+ // an undefined query would indicate queryCallback returned undefined,
81
+ // thus the request shouldn't fire as is in custom cache
82
+ let query: RequestQueryBody<Modify<RestTableInterface, RequestTableOverrides>> | undefined | null;
83
+
84
+ if ('function' === typeof queryCallback) {
85
+
86
+ query = queryCallback(this.request); // obj or obj[]
87
+
88
+ } else {
89
+
90
+ query = queryCallback;
91
+
92
+ }
93
+
94
+ if (undefined === query || null === query) {
95
+
96
+ if (this.request.debug && isLocal) {
97
+
98
+ toast.warning("DEV: queryCallback returned undefined, signaling in Custom Cache. (returning null)", toastOptionsDevs)
99
+
100
+ }
101
+
102
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + tableName + ') undefined, returning null (will not fire ajax)!', 'color: #c00')
103
+
104
+ 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')
105
+
106
+ console.trace();
107
+
108
+ console.groupEnd()
109
+
110
+ return null;
111
+
112
+ }
113
+
114
+ if (C6.GET === requestMethod) {
115
+
116
+ if (undefined === query[C6.PAGINATION]) {
117
+
118
+ query[C6.PAGINATION] = {}
119
+
120
+ }
121
+
122
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
123
+
124
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
125
+
126
+ }
127
+
128
+ // this could return itself with a new page number, or undefined if the end is reached
129
+ const apiRequest = async (): Promise<apiReturn<ResponseDataType>> => {
130
+
131
+ const {
132
+ debug,
133
+ cacheResults = (C6.GET === requestMethod),
134
+ dataInsertMultipleRows,
135
+ success,
136
+ fetchDependencies = eFetchDependencies.NONE,
137
+ error = "An unexpected API error occurred!"
138
+ } = this.request
139
+
140
+ if (C6.GET === requestMethod
141
+ && undefined !== query?.[C6.PAGINATION]?.[C6.PAGE]
142
+ && 1 !== query[C6.PAGINATION][C6.PAGE]) {
143
+
144
+ console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!')
145
+
146
+ console.log('Request Data (note you may see the success and/or error prompt):', this.request)
147
+
148
+ console.trace();
149
+
150
+ console.groupEnd()
151
+
152
+ }
153
+
154
+ // 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.
155
+ // 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
156
+
157
+ // literally impossible for query to be undefined or null here but the editor is too busy licking windows to understand that
158
+ let querySerialized: string = sortAndSerializeQueryObject(tables, query ?? {});
159
+
160
+ let cacheResult: iCacheAPI | undefined = apiRequestCache.find(cache => cache.requestArgumentsSerialized === querySerialized);
161
+
162
+ let cachingConfirmed = false;
163
+
164
+ // determine if we need to paginate.
165
+ if (requestMethod === C6.GET) {
166
+
167
+ if (undefined === query?.[C6.PAGINATION]) {
168
+
169
+ if (undefined === query || null === query) {
170
+
171
+ query = {}
172
+
173
+ }
174
+
175
+ query[C6.PAGINATION] = {}
176
+
177
+ }
178
+
179
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
180
+
181
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
182
+
183
+ // this will evaluate true most the time
184
+ if (true === cacheResults) {
185
+
186
+ // just find the next, non-fetched, page and return a function to request it
187
+ if (undefined !== cacheResult) {
188
+
189
+ do {
190
+
191
+ const cacheCheck = checkCache<ResponseDataType>(cacheResult, requestMethod, tableName, this.request);
192
+
193
+ if (false !== cacheCheck) {
194
+
195
+ return cacheCheck;
196
+
197
+ }
198
+
199
+ // this line incrementing page is why we return recursively
200
+ ++query[C6.PAGINATION][C6.PAGE];
201
+
202
+ // this json stringify is to capture the new page number
203
+ querySerialized = sortAndSerializeQueryObject(tables, query ?? {});
204
+
205
+ cacheResult = apiRequestCache.find(cache => cache.requestArgumentsSerialized === querySerialized)
206
+
207
+ } while (undefined !== cacheResult)
208
+
209
+ if (debug && isLocal) {
210
+
211
+ toast.warning("DEVS: Request in cache. (" + apiRequestCache.findIndex(cache => cache.requestArgumentsSerialized === querySerialized) + "). Returning function to request page (" + query[C6.PAGINATION][C6.PAGE] + ")", toastOptionsDevs);
212
+
213
+ }
214
+
215
+ // @ts-ignore - this is an incorrect warning on TS, it's well typed
216
+ return apiRequest;
217
+
218
+ }
219
+
220
+ cachingConfirmed = true;
221
+
222
+ } else {
223
+
224
+ if (debug && isLocal) {
225
+
226
+ toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
227
+
228
+ }
229
+
230
+ }
231
+
232
+ if (debug && isLocal) {
233
+
234
+ toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
235
+
236
+ }
237
+
238
+ } else if (cacheResults) { // if we are not getting, we are updating, deleting, or inserting
239
+
240
+ if (cacheResult) {
241
+ const cacheCheck = checkCache<ResponseDataType>(cacheResult, requestMethod, tableName, this.request);
242
+
243
+ if (false !== cacheCheck) {
244
+
245
+ return cacheCheck;
246
+
247
+ }
248
+ }
249
+
250
+ cachingConfirmed = true;
251
+ // push to cache so we do not repeat the request
252
+
253
+ }
254
+
255
+ let addBackPK: (() => void) | undefined;
256
+
257
+ let apiResponse: RestTableInterface[PrimaryKey] | string | boolean | number | undefined;
258
+
259
+ let returnGetNextPageFunction = false;
260
+
261
+ let restRequestUri: string = restURL + operatingTable + '/';
262
+
263
+ const needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
264
+ && false === skipPrimaryCheck;
265
+
266
+ const TABLES = C6.TABLES;
267
+
268
+ // todo - aggregate primary key check with condition check
269
+ // check if PK exists in query, clone so pop does not affect the real data
270
+ const primaryKey = structuredClone(TABLES[operatingTable]?.PRIMARY)?.pop()?.split('.')?.pop();
271
+
272
+ if (needsConditionOrPrimaryCheck) {
273
+
274
+ if (undefined === primaryKey) {
275
+
276
+ if (null === query
277
+ || undefined === query
278
+ || undefined === query?.[C6.WHERE]
279
+ || (true === Array.isArray(query[C6.WHERE])
280
+ || query[C6.WHERE].length === 0)
281
+ || (Object.keys(query?.[C6.WHERE]).length === 0)
282
+ ) {
283
+
284
+ console.error(query)
285
+
286
+ throw Error('Failed to parse primary key information. Query: (' + JSON.stringify(query) + ') Primary Key: (' + JSON.stringify(primaryKey) + ') TABLES[operatingTable]?.PRIMARY: (' + JSON.stringify(TABLES[operatingTable]?.PRIMARY) + ') for operatingTable (' + operatingTable + ').')
287
+
288
+ }
289
+
290
+ } else {
291
+
292
+ if (undefined === query
293
+ || null === query
294
+ || false === primaryKey in query) {
295
+
296
+ if (true === debug && isLocal) {
297
+
298
+ toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!')
299
+
300
+ }
301
+
302
+ throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(this.request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
303
+
304
+ }
305
+
306
+ if (undefined === query?.[primaryKey]
307
+ || null === query?.[primaryKey]) {
308
+
309
+ toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!')
310
+
311
+ throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
312
+
313
+ }
314
+
315
+ }
316
+
317
+ }
318
+
319
+ // A part of me exists that wants to remove this, but it's a good feature
320
+ // this allows developers the ability to cache requests based on primary key
321
+ // for tables like `photos` this can be a huge performance boost
322
+ if (undefined !== query
323
+ && null !== query
324
+ && undefined !== primaryKey
325
+ && primaryKey in query) {
326
+
327
+ restRequestUri += query[primaryKey] + '/'
328
+
329
+ const removedPkValue = query[primaryKey];
330
+
331
+ addBackPK = () => {
332
+ query ??= {}
333
+ query[primaryKey] = removedPkValue
334
+ }
335
+
336
+ delete query[primaryKey]
337
+
338
+ console.log('query', query, 'primaryKey', primaryKey, 'removedPkValue', removedPkValue)
339
+
340
+ } else {
341
+
342
+ console.log('query', query)
343
+
344
+ }
345
+
346
+ try {
347
+
348
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0')
349
+
350
+ console.log(this.request)
351
+
352
+ 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')
353
+
354
+ 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')
355
+
356
+ console.trace()
357
+
358
+ console.groupEnd()
359
+
360
+ const axiosActiveRequest: AxiosPromise<ResponseDataType> = axios![requestMethod.toLowerCase()]<ResponseDataType>(
361
+ restRequestUri,
362
+ ...((() => {
363
+
364
+ // @link - https://axios-http.com/docs/instance
365
+ // How configuration vs data is passed is variable, use documentation above for reference
366
+ if (requestMethod === GET) {
367
+
368
+ return [{
369
+ withCredentials: withCredentials,
370
+ params: query
371
+ }]
372
+
373
+ } else if (requestMethod === POST) {
374
+
375
+ if (undefined !== dataInsertMultipleRows) {
376
+
377
+ return [
378
+ dataInsertMultipleRows.map(data =>
379
+ convertForRequestBody<typeof data>(data, fullTableList, C6, (message) => toast.error(message, toastOptions))),
380
+ {
381
+ withCredentials: withCredentials,
382
+ }
383
+ ]
384
+
385
+ }
386
+
387
+ return [
388
+ convertForRequestBody<RestTableInterface>(query as RestTableInterface, fullTableList, C6, (message) => toast.error(message, toastOptions)),
389
+ {
390
+ withCredentials: withCredentials,
391
+ }
392
+ ]
393
+
394
+ } else if (requestMethod === PUT) {
395
+
396
+ return [
397
+ convertForRequestBody<RestTableInterface>(query as RestTableInterface, fullTableList, C6, (message) => toast.error(message, toastOptions)),
398
+ {
399
+ withCredentials: withCredentials,
400
+ }
401
+ ]
402
+ } else if (requestMethod === DELETE) {
403
+
404
+ return [{
405
+ withCredentials: withCredentials,
406
+ data: convertForRequestBody<RestTableInterface>(query as RestTableInterface, fullTableList, C6, (message) => toast.error(message, toastOptions))
407
+ }]
408
+
409
+ } else {
410
+
411
+ throw new Error('The request method (' + requestMethod + ') was not recognized.')
412
+
413
+ }
414
+
415
+ })())
416
+ );
417
+
418
+ if (cachingConfirmed) {
419
+
420
+ // push to cache so we do not repeat the request
421
+ apiRequestCache.push({
422
+ requestArgumentsSerialized: querySerialized,
423
+ request: axiosActiveRequest
424
+ });
425
+
426
+ }
427
+
428
+ // todo - wip verify this works
429
+ // we had removed the value from the request to add to the URI.
430
+ addBackPK?.(); // adding back so post-processing methods work
431
+
432
+ // returning the promise with this then is important for tests. todo - we could make that optional.
433
+ // https://rapidapi.com/guides/axios-async-await
434
+ return axiosActiveRequest.then(async (response): Promise<AxiosResponse<ResponseDataType, any>> => {
435
+
436
+ if (typeof response.data === 'string') {
437
+
438
+ if (isTest) {
439
+
440
+ console.trace()
441
+
442
+ throw new Error('The response data was a string this typically indicated html was sent. Make sure all cookies (' + JSON.stringify(response.config.headers) + ') needed are present! (' + response.data + ')')
443
+
444
+ }
445
+
446
+ return Promise.reject(response);
447
+
448
+ }
449
+
450
+ if (cachingConfirmed) {
451
+
452
+ const cacheIndex = apiRequestCache.findIndex(cache => cache.requestArgumentsSerialized === querySerialized);
453
+
454
+ apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction
455
+
456
+ // only cache get method requests
457
+ apiRequestCache[cacheIndex].response = response
458
+
459
+ }
460
+
461
+ apiResponse = TestRestfulResponse(response, success, error)
462
+
463
+ if (false === apiResponse) {
464
+
465
+ if (debug && isLocal) {
466
+
467
+ toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
468
+
469
+ }
470
+
471
+ return response;
472
+
473
+ }
474
+
475
+ // stateful operations are done in the response callback - its leverages rest generated functions
476
+ if (responseCallback) {
477
+
478
+ responseCallback(response, this.request, apiResponse)
479
+
480
+ }
481
+
482
+ if (C6.GET === requestMethod) {
483
+
484
+ const responseData = response.data as iGetC6RestResponse<any>;
485
+
486
+ returnGetNextPageFunction = 1 !== query?.[C6.PAGINATION]?.[C6.LIMIT] &&
487
+ query?.[C6.PAGINATION]?.[C6.LIMIT] === responseData.rest.length
488
+
489
+ if (false === isTest || true === isVerbose) {
490
+
491
+ console.groupCollapsed('%c API: Response (' + requestMethod + ' ' + tableName + ') returned length (' + responseData.rest?.length + ') of possible (' + query?.[C6.PAGINATION]?.[C6.LIMIT] + ') limit!', 'color: #0c0')
492
+
493
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0')
494
+
495
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', this.request)
496
+
497
+ console.log('%c Response Data:', 'color: #0c0', responseData.rest)
498
+
499
+ console.log('%c Will return get next page function:' + (1 !== query?.[C6.PAGINATION]?.[C6.LIMIT] ? '' : ' (Will not return with explicit limit 1 set)'), 'color: #0c0', true === returnGetNextPageFunction)
500
+
501
+ console.trace();
502
+
503
+ console.groupEnd()
504
+
505
+ }
506
+
507
+ if (false === returnGetNextPageFunction
508
+ && true === debug
509
+ && isLocal) {
510
+
511
+ toast.success("DEVS: Response returned length (" + responseData.rest?.length + ") less than limit (" + query?.[C6.PAGINATION]?.[C6.LIMIT] + ").", toastOptionsDevs);
512
+
513
+ }
514
+
515
+
516
+ if (fetchDependencies
517
+ && 'number' === typeof fetchDependencies
518
+ && responseData.rest.length > 0) {
519
+
520
+ console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
521
+ + (fetchDependencies & eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
522
+ + (fetchDependencies & eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
523
+ + (fetchDependencies & eFetchDependencies.C6ENTITY ? ' | (C6ENTITY)' : '')
524
+ + (fetchDependencies & eFetchDependencies.RECURSIVE ? ' | (RECURSIVE)' : ''), 'color: #33ccff')
525
+
526
+ console.groupCollapsed('Collapsed JS Trace');
527
+ console.trace(); // hidden in collapsed group
528
+ console.groupEnd();
529
+
530
+ // noinspection JSBitwiseOperatorUsage
531
+ let dependencies: {
532
+ [key: string]: iConstraint[]
533
+ } = {};
534
+
535
+ if (fetchDependencies & eFetchDependencies.C6ENTITY) {
536
+
537
+ dependencies = operatingTable.endsWith("carbon_carbons")
538
+ ? {
539
+ // the context of the entity system is a bit different
540
+ ...fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
541
+ ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
542
+ : {},
543
+ ...fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
544
+ ? C6.TABLES[operatingTable].TABLE_REFERENCES
545
+ : {}
546
+ } : {
547
+ // the context of the entity system is a bit different
548
+ ...fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
549
+ ? {
550
+ ...Object.keys(C6.TABLES[operatingTable].TABLE_REFERENCES).reduce((accumulator, columnName) => {
551
+
552
+ if (!C6.TABLES[operatingTable].PRIMARY_SHORT.includes(columnName)) {
553
+ accumulator[columnName] = C6.TABLES[operatingTable].TABLE_REFERENCES[columnName]
554
+ }
555
+
556
+ return accumulator
557
+ }, {}),
558
+ ...C6.TABLES[operatingTable].TABLE_REFERENCED_BY // it is unlikely that a C6 table will have any TABLE_REFERENCED_BY
559
+ }
560
+ : {},
561
+ ...fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
562
+ ? C6.TABLES[operatingTable].PRIMARY_SHORT.reduce((accumulator, primaryKey) => {
563
+ if (primaryKey in C6.TABLES[operatingTable].TABLE_REFERENCES) {
564
+ accumulator[primaryKey] = C6.TABLES[operatingTable].TABLE_REFERENCES[primaryKey]
565
+ }
566
+ return accumulator
567
+ }, {})
568
+ : {}
569
+ }
570
+
571
+ } else {
572
+
573
+ // this is the natural mysql context
574
+ dependencies = {
575
+ ...fetchDependencies & eFetchDependencies.REFERENCED // REFERENCED === CHILDREN
576
+ ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
577
+ : {},
578
+ ...fetchDependencies & eFetchDependencies.REFERENCES // REFERENCES === PARENTS
579
+ ? C6.TABLES[operatingTable].TABLE_REFERENCES
580
+ : {}
581
+ };
582
+
583
+ }
584
+
585
+ let fetchReferences: {
586
+ [externalTable: string]: {
587
+ [column: string]: string[]
588
+ }
589
+ } = {}
590
+
591
+ let apiRequestPromises: Array<apiReturn<iGetC6RestResponse<any>>> = []
592
+
593
+ console.log('%c Dependencies', 'color: #005555', dependencies)
594
+
595
+ Object.keys(dependencies)
596
+ .forEach(column => dependencies[column]
597
+ .forEach((constraint) => {
598
+
599
+ const columnValues = responseData.rest[column] ?? responseData.rest.map((row) => {
600
+
601
+ if (operatingTable.endsWith("carbons")
602
+ && 'entity_tag' in row
603
+ && !constraint.TABLE.endsWith(row['entity_tag'].split('\\').pop().toLowerCase())) {
604
+
605
+ return false; // map
606
+
607
+ }
608
+
609
+ if (!(column in row)) {
610
+ return false
611
+ }
612
+
613
+ // todo - row[column] is a FK value, we should optionally remove values that are already in state
614
+ // this could be any column in the table constraint.TABLE, not just the primary key
615
+
616
+ return row[column]
617
+
618
+ }).filter(n => n) ?? [];
619
+
620
+ if (columnValues.length === 0) {
621
+
622
+ return; // forEach
623
+
624
+ }
625
+
626
+ fetchReferences[constraint.TABLE] ??= {};
627
+
628
+ fetchReferences[constraint.TABLE][constraint.COLUMN] ??= []
629
+
630
+ fetchReferences[constraint.TABLE][constraint.COLUMN].push(columnValues)
631
+
632
+ }));
633
+
634
+ console.log('fetchReferences', fetchReferences)
635
+
636
+ for (const tableToFetch in fetchReferences) {
637
+
638
+ if (fetchDependencies & eFetchDependencies.C6ENTITY
639
+ && 'string' === typeof tableName
640
+ && tableName.endsWith("carbon_carbons")) {
641
+
642
+ // todo - rethink the table ref entity system - when tables are renamed? no hooks exist in mysql
643
+ // since were already filtering on column, we can assume the first row constraint is the same as the rest
644
+
645
+ const referencesTables: string[] = responseData.rest.reduce((accumulator: string[], row: {
646
+ [x: string]: string;
647
+ }) => {
648
+ if ('entity_tag' in row && !accumulator.includes(row['entity_tag'])) {
649
+ accumulator.push(row['entity_tag']);
650
+ }
651
+ return accumulator;
652
+ }, []).map((entityTag) => entityTag.split('\\').pop().toLowerCase());
653
+
654
+ const shouldContinue = referencesTables.find((referencesTable) => tableToFetch.endsWith(referencesTable))
655
+
656
+ if (!shouldContinue) {
657
+
658
+ console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables)
659
+
660
+ continue;
661
+
662
+ }
663
+
664
+ console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') will be fetched.', 'color: #0c0')
665
+
666
+ }
667
+
668
+ const fetchTable = await C6.IMPORT(tableToFetch)
669
+
670
+ const RestApi = fetchTable.default
671
+
672
+ console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff')
673
+
674
+ let nextFetchDependencies = eFetchDependencies.NONE
675
+
676
+ if (fetchDependencies & eFetchDependencies.RECURSIVE) {
677
+
678
+ if (fetchDependencies & eFetchDependencies.ALL) {
679
+
680
+ throw Error('Recursive fetch dependencies with both PARENT and CHILD reference will result in an infin1ite loop. As there is not real ending condition, this is not supported.')
681
+
682
+ }
683
+
684
+ nextFetchDependencies = fetchDependencies
685
+
686
+ } else if (fetchDependencies & eFetchDependencies.C6ENTITY) {
687
+
688
+ if (tableToFetch === "carbon_carbons") {
689
+
690
+ nextFetchDependencies = fetchDependencies
691
+
692
+ } else {
693
+
694
+ nextFetchDependencies = fetchDependencies ^ eFetchDependencies.C6ENTITY
695
+
696
+ }
697
+
698
+ }
699
+
700
+ console.log('fetchReferences', fetchReferences[tableToFetch], "Current fetchDependencies for (" + operatingTable + "):", fetchDependencies, "New fetchDependencies for (" + tableToFetch + "): ", nextFetchDependencies)
701
+
702
+ // todo - filter out ids that exist in state?!? note - remember that this does not necessarily mean the pk, but only known is its an FK to somewhere
703
+ // it not certain that they are using carbons' entities either
704
+
705
+ // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
706
+ // todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
707
+ apiRequestPromises.push(RestApi.Get({
708
+ [C6.WHERE]: {
709
+ 0: Object.keys(fetchReferences[tableToFetch]).reduce((sum, column) => {
710
+
711
+ fetchReferences[tableToFetch][column] = fetchReferences[tableToFetch][column].flat(Infinity)
712
+
713
+ if (0 === fetchReferences[tableToFetch][column].length) {
714
+
715
+ console.warn('The column (' + column + ') was not found in the response data. We will not fetch.', responseData)
716
+
717
+ return false;
718
+
719
+ }
720
+
721
+ sum[column] = fetchReferences[tableToFetch][column].length === 1
722
+ ? fetchReferences[tableToFetch][column][0]
723
+ : [
724
+ C6.IN, fetchReferences[tableToFetch][column]
725
+ ]
726
+
727
+ return sum
728
+
729
+ }, {})
730
+ },
731
+ fetchDependencies: nextFetchDependencies
732
+ }
733
+ ));
734
+
735
+ }
736
+
737
+ console.groupEnd()
738
+
739
+ await Promise.all(apiRequestPromises)
740
+
741
+ apiRequestPromises.map(async (promise) => {
742
+ if (!Array.isArray(this.request.fetchDependencies)) {
743
+ // to reassign value we must ref the root
744
+ this.request.fetchDependencies = [];
745
+ }
746
+ this.request.fetchDependencies.push(await promise)
747
+ })
748
+
749
+ }
750
+
751
+
752
+ }
753
+
754
+ if (debug && isLocal) {
755
+
756
+ toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
757
+
758
+ }
759
+
760
+ return response;
761
+
762
+ }
763
+ );
764
+
765
+ } catch (throwableError) {
766
+
767
+ if (isTest) {
768
+
769
+ throw new Error(JSON.stringify(throwableError))
770
+
771
+ }
772
+
773
+ console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000')
774
+
775
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0')
776
+
777
+ console.warn(throwableError)
778
+
779
+ console.trace()
780
+
781
+ console.groupEnd()
782
+
783
+ TestRestfulResponse(throwableError, success, error)
784
+
785
+ return null;
786
+
787
+ }
788
+
789
+ }
790
+
791
+ return await apiRequest()
792
+
793
+ }
794
+ }