@carbonorm/carbonnode 1.0.0 → 1.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.
@@ -0,0 +1,815 @@
1
+ import convertForRequestBody from "api/convertForRequestBody";
2
+ import {C6RestfulModel} from "api/interfaces/ormInterfaces";
3
+ import {AxiosInstance, AxiosPromise, AxiosResponse} from "axios";
4
+
5
+ import {toast} from "react-toastify";
6
+ import isLocal from "variables/isLocal";
7
+ import isTest from "variables/isTest";
8
+ import isVerbose from "variables/isVerbose";
9
+ import {toastOptions, toastOptionsDevs} from "variables/toastOptions";
10
+
11
+ // todo - use bootstrap, it currently is prefixed with an underscore to denote to TS that we are aware it is unused.
12
+ // When we capture DropExceptions and display them as a custom page, this will change.
13
+ export function TestRestfulResponse(response: AxiosResponse | any, success: ((r: AxiosResponse) => (string | void)) | string | undefined, error: ((r: AxiosResponse) => (string | void)) | string | undefined): string | boolean | number {
14
+
15
+ if (undefined === response.data?.['ERROR TYPE']
16
+ && (undefined !== response?.data?.rest
17
+ || undefined !== response.data?.created
18
+ || undefined !== response.data?.updated
19
+ || undefined !== response.data?.deleted)) {
20
+
21
+ let successReturn: string | undefined | void = 'function' === typeof success ? success?.(response) : success;
22
+
23
+ if (typeof successReturn === 'string') {
24
+
25
+ toast.success(successReturn, toastOptions);
26
+
27
+ }
28
+
29
+ // this could end up with bad results for deleting id's === 0
30
+ return response.data.created ?? response.data.updated ?? response.data.deleted ?? true;
31
+
32
+ }
33
+
34
+ let errorReturn: string | undefined | void = 'function' === typeof error ? error?.(response) : error;
35
+
36
+ if (typeof errorReturn === 'string') {
37
+
38
+ toast.error(errorReturn, toastOptions);
39
+
40
+ }
41
+
42
+ return false;
43
+
44
+
45
+ }
46
+
47
+ export function removeInvalidKeys<iRestObject>(request: any, c6Tables: (C6RestfulModel)[]): iRestObject {
48
+
49
+ let intersection: iRestObject = {} as iRestObject
50
+
51
+ let restfulObjectKeys: string[] = [];
52
+
53
+ c6Tables.forEach(table => Object.values(table.COLUMNS).forEach(column => {
54
+
55
+ if (false === restfulObjectKeys.includes(column)) {
56
+
57
+ restfulObjectKeys.push(column)
58
+
59
+ }
60
+
61
+ }))
62
+
63
+ Object.keys(request).forEach(key => {
64
+
65
+ if (restfulObjectKeys.includes(key)) {
66
+
67
+ intersection[key] = request[key]
68
+
69
+ }
70
+
71
+ });
72
+
73
+ isTest || console.log('intersection', intersection)
74
+
75
+ return intersection
76
+
77
+ }
78
+
79
+ // if you can get away with modify over modifyDeep, use modify. The editor will be happier.
80
+ export type Modify<T, R> = Omit<T, keyof R> & R;
81
+
82
+ // @link https://stackoverflow.com/questions/41285211/overriding-interface-property-type-defined-in-typescript-d-ts-file/55032655#55032655
83
+ export type ModifyDeep<A, B extends DeepPartialAny<A>> = {
84
+ [K in keyof A | keyof B]?: // For all keys in A and B:
85
+ K extends keyof A // ───┐
86
+ ? K extends keyof B // ───┼─ key K exists in both A and B
87
+ ? A[K] extends AnyObject // │ ┴──┐
88
+ ? B[K] extends AnyObject // │ ───┼─ both A and B are objects
89
+ ? ModifyDeep<A[K], B[K]> // │ │ └─── We need to go deeper (recursively)
90
+ : B[K] // │ ├─ B is a primitive 🠆 use B as the final type (new type)
91
+ : B[K] // │ └─ A is a primitive 🠆 use B as the final type (new type)
92
+ : A[K] // ├─ key only exists in A 🠆 use A as the final type (original type)
93
+ : B[K] // └─ key only exists in B 🠆 use B as the final type (new type)
94
+ }
95
+
96
+ type AnyObject = Record<string, any>
97
+
98
+ // This type is here only for some intellisense for the overrides object
99
+ type DeepPartialAny<T> = {
100
+ /** Makes each property optional and turns each leaf property into any, allowing for type overrides by narrowing any. */
101
+ [P in keyof T]?: T[P] extends AnyObject ? DeepPartialAny<T[P]> : any
102
+ }
103
+
104
+ export type iAPI<RestTableInterfaces extends { [key: string]: any }> = RestTableInterfaces & {
105
+ dataInsertMultipleRows?: RestTableInterfaces[],
106
+ cacheResults?: boolean, // aka ignoreCache
107
+ fetchDependencies?: boolean,
108
+ debug?: boolean,
109
+ success?: string | ((r: AxiosResponse) => (string | void)),
110
+ error?: string | ((r: AxiosResponse) => (string | void)),
111
+ blocking?: boolean
112
+ }
113
+
114
+ interface iCacheAPI<ResponseDataType = any> {
115
+ requestArgumentsSerialized: string,
116
+ request: AxiosPromise<ResponseDataType>,
117
+ response?: AxiosResponse,
118
+ final?: boolean,
119
+ }
120
+
121
+
122
+ // do not remove entries from this array. It is used to track the progress of API requests.
123
+ // position in array is important. Do not sort. To not add to begging.
124
+ let apiRequestCache: iCacheAPI[] = [];
125
+
126
+ let userCustomClearCache: (() => void)[] = [];
127
+
128
+ export function checkAllRequestsComplete(): true | (string[]) {
129
+
130
+ const stillRunning = apiRequestCache.filter((cache) => undefined === cache.response)
131
+
132
+ if (stillRunning.length !== 0) {
133
+
134
+ if (document === null || document === undefined) {
135
+
136
+ throw new Error('document is undefined while waiting for API requests to complete (' + JSON.stringify(apiRequestCache) + ')')
137
+
138
+ }
139
+
140
+ // when requests return emtpy sets in full renders, it may not be possible to track their progress.
141
+ console.warn('stillRunning...', stillRunning)
142
+
143
+ return stillRunning.map((cache) => cache.requestArgumentsSerialized)
144
+
145
+ }
146
+
147
+ return true
148
+
149
+ }
150
+
151
+
152
+ interface iClearCache {
153
+ ignoreWarning: boolean
154
+ }
155
+
156
+
157
+ function checkCache<ResponseDataType = any, RestShortTableNames = string>(cacheResult: iCacheAPI<ResponseDataType>, requestMethod: string, tableName: RestShortTableNames | RestShortTableNames[], request: any): false | undefined | null | AxiosPromise<ResponseDataType> {
158
+
159
+ if (undefined === cacheResult?.response) {
160
+
161
+ console.groupCollapsed('%c API: The request on (' + tableName + ') is in cache and the response is undefined. The request has not finished. Returning the request Promise!', 'color: #0c0')
162
+
163
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0')
164
+
165
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', request)
166
+
167
+ console.groupEnd()
168
+
169
+ return cacheResult.request;
170
+
171
+ }
172
+
173
+ if (true === cacheResult?.final) {
174
+
175
+ if (false === isTest || true === isVerbose) {
176
+
177
+ console.groupCollapsed('%c API: rest api cache has reached the final result. Returning undefined!', 'color: #cc0')
178
+
179
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #cc0')
180
+
181
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #cc0', request)
182
+
183
+ console.log('%c Response Data:', 'color: #cc0', cacheResult?.response?.data?.rest || cacheResult?.response?.data || cacheResult?.response)
184
+
185
+ console.groupEnd()
186
+
187
+ }
188
+
189
+ return undefined;
190
+
191
+ }
192
+
193
+ return false;
194
+ }
195
+
196
+ function sortAndSerializeQueryObject(tables: String, query: Object) {
197
+ const orderedQuery = Object.keys(query).sort().reduce(
198
+ (obj, key) => {
199
+ obj[key] = query[key];
200
+ return obj;
201
+ },
202
+ {}
203
+ );
204
+
205
+ return tables + ' ' + JSON.stringify(orderedQuery);
206
+ }
207
+
208
+
209
+ export function clearCache(props?: iClearCache) {
210
+
211
+ if (false === props?.ignoreWarning) {
212
+
213
+ console.warn('The rest api clearCache should only be used with extreme care! Avoid using this in favor of using `cacheResults : boolean`.')
214
+
215
+ }
216
+
217
+ userCustomClearCache.map((f) => 'function' === typeof f && f());
218
+
219
+ userCustomClearCache = apiRequestCache = []
220
+
221
+ }
222
+
223
+ /**
224
+ * the first argument ....
225
+ *
226
+ * Our api returns a zero argument function iff the method is get and the previous request reached the predefined limit.
227
+ * This function can be aliased as GetNextPageOfResults(). If the end is reached undefined will be returned.
228
+ *
229
+ *
230
+ * For POST, PUT, and DELETE requests one can expect the primary key of the new or modified index, or a boolean success
231
+ * indication if no primary key exists.
232
+ **/
233
+ export const POST = 'POST';
234
+
235
+ export const PUT = 'PUT';
236
+
237
+
238
+ export const GET = 'GET';
239
+
240
+
241
+ export const DELETE = 'DELETE';
242
+
243
+
244
+ // returning undefined means no more results are available, thus we've queried everything possible
245
+ // null means the request is currently being executed
246
+ // https://www.typescriptlang.org/docs/handbook/2/conditional-types.html
247
+ export type apiReturn<Response> =
248
+ null
249
+ | undefined
250
+ | AxiosPromise<Response>
251
+ | (Response extends iGetC6RestResponse<any> ? (() => apiReturn<Response>) : null)
252
+
253
+
254
+ export type iRestMethods = 'GET' | 'POST' | 'PUT' | 'DELETE';
255
+
256
+
257
+ //wip
258
+ export type RequestGetPutDeleteBody = {
259
+ SELECT?: any,
260
+ UPDATE?: any,
261
+ DELETE?: any,
262
+ WHERE?: any,
263
+ JOIN?: {
264
+ LEFT?: any,
265
+ RIGHT?: any,
266
+ INNER?: any,
267
+ },
268
+ PAGINATION?: {
269
+ PAGE?: number,
270
+ LIMIT?: number,
271
+ }
272
+ }
273
+
274
+ export type RequestQueryBody<RestTableInterfaces extends { [key: string]: any }> =
275
+ iAPI<RestTableInterfaces>
276
+ | RequestGetPutDeleteBody;
277
+
278
+ export function isPromise(x) {
279
+ return Object(x).constructor === Promise
280
+ }
281
+
282
+ interface iC6RestResponse<RestData> {
283
+ rest: RestData,
284
+ session?: any,
285
+ sql?: any
286
+ }
287
+
288
+
289
+ interface iChangeC6Data {
290
+ rowCount: number,
291
+ }
292
+
293
+ export interface iDeleteC6RestResponse<RestData = any, RequestData = any> extends iChangeC6Data, iC6RestResponse<RestData> {
294
+ deleted: boolean | number | string | RequestData,
295
+ }
296
+
297
+ export interface iPostC6RestResponse<RestData = any> extends iC6RestResponse<RestData> {
298
+ created: boolean | number | string,
299
+ }
300
+
301
+ export interface iPutC6RestResponse<RestData = any, RequestData = any> extends iChangeC6Data, iC6RestResponse<RestData> {
302
+ updated: boolean | number | string | RequestData,
303
+ }
304
+
305
+ export type iGetC6RestResponse<ResponseDataType, ResponseDataOverrides = {}> = iC6RestResponse<Modify<ResponseDataType, ResponseDataOverrides>[]>
306
+
307
+ interface iRest<CustomAndRequiredFields extends { [key: string]: any }, RestTableInterfaces extends {
308
+ [key: string]: any
309
+ }, RequestTableOverrides = { [key in keyof RestTableInterfaces]: any }, ResponseDataType = any, RestShortTableNames extends string = any> {
310
+ C6: { TABLES: { [key: string]: C6RestfulModel & { [key: string]: string | number } } } & { [key: string]: string },
311
+ axios: AxiosInstance,
312
+ restURL: string,
313
+ tableName: RestShortTableNames | RestShortTableNames[],
314
+ requestMethod: iRestMethods,
315
+ clearCache?: () => void,
316
+ skipPrimaryCheck?: boolean,
317
+ queryCallback: RequestQueryBody<Modify<RestTableInterfaces, RequestTableOverrides>> | ((request: iAPI<Modify<RestTableInterfaces, RequestTableOverrides>> & CustomAndRequiredFields) => (null | undefined | RequestQueryBody<Modify<RestTableInterfaces, RequestTableOverrides>>)),
318
+ responseCallback: (response: AxiosResponse<ResponseDataType>,
319
+ request: iAPI<Modify<RestTableInterfaces, RequestTableOverrides>> & CustomAndRequiredFields,
320
+ success: (ResponseDataType extends iPutC6RestResponse | iDeleteC6RestResponse ? RequestQueryBody<Modify<RestTableInterfaces, RequestTableOverrides>> : string) | string | number | boolean) => any // keep this set to any, it allows easy arrow functions and the results unused here
321
+ }
322
+
323
+ export function extendedTypeHints<RestTableInterfaces extends {
324
+ [key: string]: any
325
+ }, RestShortTableNames extends string>() {
326
+ return <CustomAndRequiredFields extends {
327
+ [key: string]: any
328
+ } = any, RequestTableTypes extends RestTableInterfaces = any, RequestTableOverrides extends {
329
+ [key: string]: any
330
+ } = any, ResponseDataType extends {
331
+ [key: string]: any
332
+ } = any>(argv) => restApi<CustomAndRequiredFields, RequestTableTypes, RequestTableOverrides, ResponseDataType, RestShortTableNames>(argv)
333
+ }
334
+
335
+ export default function restApi<
336
+ CustomAndRequiredFields extends {
337
+ [key: string]: any;
338
+ } = any,
339
+ RestTableInterfaces extends {
340
+ [key: string]: any
341
+ } = any,
342
+ RequestTableOverrides extends {
343
+ [key: string]: any;
344
+ } = any, ResponseDataType = any,
345
+ RestShortTableNames extends string = any
346
+ >({
347
+ C6,
348
+ axios,
349
+ restURL,
350
+ tableName,
351
+ requestMethod = GET,
352
+ queryCallback = {},
353
+ responseCallback,
354
+ skipPrimaryCheck = false,
355
+ clearCache = undefined
356
+ }: iRest<CustomAndRequiredFields, RestTableInterfaces, RequestTableOverrides, ResponseDataType, RestShortTableNames>
357
+ ) {
358
+
359
+ const fullTableList = Array.isArray(tableName) ? tableName : [tableName];
360
+
361
+ const operatingTable = fullTableList[0];
362
+
363
+ const tables = fullTableList.join(',')
364
+
365
+ switch (requestMethod) {
366
+ case GET:
367
+ case POST:
368
+ case PUT:
369
+ case DELETE:
370
+ break;
371
+ default:
372
+ throw Error('Bad request method passed to getApi')
373
+ }
374
+
375
+ if (null !== clearCache || undefined !== clearCache) {
376
+
377
+ userCustomClearCache[tables + requestMethod] = clearCache;
378
+
379
+ }
380
+
381
+ return (request: iAPI<Modify<RestTableInterfaces, RequestTableOverrides>> & CustomAndRequiredFields = {} as iAPI<Modify<RestTableInterfaces, RequestTableOverrides>> & CustomAndRequiredFields) => {
382
+
383
+ // an undefined query would indicate queryCallback returned undefined,
384
+ // thus the request shouldn't fire as is in custom cache
385
+ let query: RequestQueryBody<Modify<RestTableInterfaces, RequestTableOverrides>> | undefined | null;
386
+
387
+ if ('function' === typeof queryCallback) {
388
+
389
+ query = queryCallback(request); // obj or obj[]
390
+
391
+ } else {
392
+
393
+ query = queryCallback;
394
+
395
+ }
396
+
397
+ if (undefined === query || null === query) {
398
+
399
+ if (request.debug && isLocal) {
400
+
401
+ toast.warning("DEV: queryCallback returned undefined, signaling in Custom Cache. (returning null)", toastOptionsDevs)
402
+
403
+ }
404
+
405
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') undefined, returning null (will not fire ajax)!', 'color: #c00')
406
+
407
+ 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')
408
+
409
+ console.trace();
410
+
411
+ console.groupEnd()
412
+
413
+ return null;
414
+
415
+ }
416
+
417
+ if (C6.GET === requestMethod) {
418
+
419
+ if (undefined === query[C6.PAGINATION]) {
420
+
421
+ query[C6.PAGINATION] = {}
422
+
423
+ }
424
+
425
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
426
+
427
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
428
+
429
+ }
430
+
431
+ // this could return itself with a new page number, or undefined if the end is reached
432
+ function apiRequest(): apiReturn<ResponseDataType> {
433
+
434
+ request.cacheResults ??= (C6.GET === requestMethod)
435
+
436
+ if (C6.GET === requestMethod
437
+ && undefined !== query?.[C6.PAGINATION]?.[C6.PAGE]
438
+ && 1 !== query[C6.PAGINATION][C6.PAGE]) {
439
+
440
+ console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!')
441
+
442
+ console.log('Request Data (note you may see the success and/or error prompt):', request)
443
+
444
+ console.trace();
445
+
446
+ console.groupEnd()
447
+
448
+ }
449
+
450
+ // 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.
451
+ // 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
452
+
453
+ // literally impossible for query to be undefined or null here but the editor is too busy licking windows to understand that
454
+ let querySerialized: string = sortAndSerializeQueryObject(tables, query ?? {});
455
+
456
+ let cacheResult: iCacheAPI | undefined = apiRequestCache.find(cache => cache.requestArgumentsSerialized === querySerialized);
457
+
458
+ let cachingConfirmed = false;
459
+
460
+ // determine if we need to paginate.
461
+ if (requestMethod === C6.GET) {
462
+
463
+ if (undefined === query?.[C6.PAGINATION]) {
464
+
465
+ if (undefined === query || null === query) {
466
+
467
+ query = {}
468
+
469
+ }
470
+
471
+ query[C6.PAGINATION] = {}
472
+
473
+ }
474
+
475
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
476
+
477
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
478
+
479
+ // this will evaluate true most the time
480
+ if (true === request.cacheResults) {
481
+
482
+ // just find the next, non-fetched, page and return a function to request it
483
+ if (undefined !== cacheResult) {
484
+
485
+ do {
486
+
487
+ const cacheCheck = checkCache<ResponseDataType>(cacheResult, requestMethod, tableName, request);
488
+
489
+ if (false !== cacheCheck) {
490
+
491
+ return cacheCheck;
492
+
493
+ }
494
+
495
+ // this line incrementing page is why we return recursively
496
+ ++query[C6.PAGINATION][C6.PAGE];
497
+
498
+ // this json stringify is to capture the new page number
499
+ querySerialized = sortAndSerializeQueryObject(tables, query ?? {});
500
+
501
+ cacheResult = apiRequestCache.find(cache => cache.requestArgumentsSerialized === querySerialized)
502
+
503
+ } while (undefined !== cacheResult)
504
+
505
+ if (request.debug && isLocal) {
506
+
507
+ toast.warning("DEVS: Request in cache. (" + apiRequestCache.findIndex(cache => cache.requestArgumentsSerialized === querySerialized) + "). Returning function to request page (" + query[C6.PAGINATION][C6.PAGE] + ")", toastOptionsDevs);
508
+
509
+ }
510
+
511
+ // @ts-ignore - this is an incorrect warning on TS, it's well typed
512
+ return apiRequest;
513
+
514
+ }
515
+
516
+ cachingConfirmed = true;
517
+
518
+ } else {
519
+
520
+ if (request.debug && isLocal) {
521
+
522
+ toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
523
+
524
+ }
525
+
526
+ }
527
+
528
+ if (request.debug && isLocal) {
529
+
530
+ toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
531
+
532
+ }
533
+
534
+ } else if (request.cacheResults) { // if we are not getting, we are updating, deleting, or inserting
535
+
536
+ if (cacheResult) {
537
+ const cacheCheck = checkCache<ResponseDataType>(cacheResult, requestMethod, tableName, request);
538
+
539
+ if (false !== cacheCheck) {
540
+
541
+ return cacheCheck;
542
+
543
+ }
544
+ }
545
+
546
+ cachingConfirmed = true;
547
+ // push to cache so we do not repeat the request
548
+
549
+ }
550
+
551
+ let addBackPK: (() => void) | undefined;
552
+
553
+ let apiResponse: string | boolean | number | undefined;
554
+
555
+ let returnGetNextPageFunction = false;
556
+
557
+ let restRequestUri: string = restURL + operatingTable + '/';
558
+
559
+ const needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
560
+ && false === skipPrimaryCheck;
561
+
562
+ const TABLES = C6.TABLES;
563
+
564
+ // todo - aggregate primary key check with condition check
565
+ // check if PK exists in query, clone so pop does not affect the real data
566
+ const primaryKey = structuredClone(TABLES[operatingTable]?.PRIMARY)?.pop()?.split('.')?.pop();
567
+
568
+ if (needsConditionOrPrimaryCheck) {
569
+
570
+ if (undefined === primaryKey) {
571
+
572
+ if (null === query
573
+ || undefined === query
574
+ || undefined === query?.[C6.WHERE]
575
+ || (true === Array.isArray(query[C6.WHERE])
576
+ || query[C6.WHERE].length === 0)
577
+ || (Object.keys(query?.[C6.WHERE]).length === 0)
578
+ ) {
579
+
580
+ console.error(query)
581
+
582
+ throw Error('Failed to parse primary key information(' + JSON.stringify(query) + JSON.stringify(primaryKey) + ')' + JSON.stringify(TABLES[operatingTable]?.PRIMARY) + ' for table (' + operatingTable + ').')
583
+
584
+ }
585
+
586
+ } else {
587
+
588
+ if (undefined === query
589
+ || null === query
590
+ || false === primaryKey in query) {
591
+
592
+ if (true === request.debug && isLocal) {
593
+
594
+ toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!')
595
+
596
+ }
597
+
598
+ throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
599
+
600
+ }
601
+
602
+ if (undefined === query?.[primaryKey]
603
+ || null === query?.[primaryKey]) {
604
+
605
+ toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!')
606
+
607
+ throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
608
+
609
+ }
610
+
611
+ }
612
+
613
+ }
614
+
615
+ // todo - remove
616
+ if (undefined !== query
617
+ && null !== query
618
+ && undefined !== primaryKey
619
+ && primaryKey in query) {
620
+
621
+ restRequestUri += query[primaryKey] + '/'
622
+
623
+ const removedPkValue = query[primaryKey];
624
+
625
+ addBackPK = () => {
626
+ query ??= {}
627
+ query[primaryKey] = removedPkValue
628
+ }
629
+
630
+ delete query[primaryKey]
631
+
632
+ }
633
+
634
+ try {
635
+
636
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0')
637
+
638
+ console.log(request)
639
+
640
+ 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')
641
+
642
+ 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')
643
+
644
+ console.trace()
645
+
646
+ console.groupEnd()
647
+
648
+ const axiosActiveRequest: AxiosPromise<ResponseDataType> = axios[requestMethod.toLowerCase()]<ResponseDataType>(
649
+ restRequestUri,
650
+ (() => {
651
+
652
+ // we had removed the value from the request to add to the URI.
653
+ addBackPK?.(); // adding back so post-processing methods work
654
+
655
+ if (requestMethod === GET) {
656
+
657
+ return {
658
+ params: query
659
+ }
660
+
661
+ } else if (requestMethod === POST) {
662
+
663
+ if (undefined !== request?.dataInsertMultipleRows) {
664
+
665
+ return request.dataInsertMultipleRows.map(data =>
666
+ convertForRequestBody<typeof data>(data, fullTableList, (message) => toast.error(message, toastOptions)));
667
+
668
+ }
669
+
670
+ return convertForRequestBody<RestTableInterfaces>(query as RestTableInterfaces, fullTableList, (message) => toast.error(message, toastOptions))
671
+
672
+ } else if (requestMethod === PUT) {
673
+
674
+ return convertForRequestBody<RestTableInterfaces>(query as RestTableInterfaces, fullTableList, (message) => toast.error(message, toastOptions))
675
+
676
+ } else if (requestMethod === DELETE) {
677
+
678
+ return {
679
+ data: convertForRequestBody<RestTableInterfaces>(query as RestTableInterfaces, fullTableList, (message) => toast.error(message, toastOptions))
680
+ }
681
+
682
+ } else {
683
+
684
+ throw new Error('The request method (' + requestMethod + ') was not recognized.')
685
+
686
+ }
687
+
688
+ })()
689
+ );
690
+
691
+ if (cachingConfirmed) {
692
+
693
+ // push to cache so we do not repeat the request
694
+ apiRequestCache.push({
695
+ requestArgumentsSerialized: querySerialized,
696
+ request: axiosActiveRequest
697
+ });
698
+
699
+ }
700
+
701
+ // https://rapidapi.com/guides/axios-async-await
702
+ return axiosActiveRequest.then(response => {
703
+
704
+ if (typeof response.data === 'string') {
705
+
706
+ if (isTest) {
707
+
708
+ console.trace()
709
+
710
+ 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 + ')')
711
+
712
+ }
713
+
714
+ return Promise.reject(response);
715
+
716
+ }
717
+
718
+ apiResponse = TestRestfulResponse(response, request?.success, request?.error ?? "An unexpected API error occurred!")
719
+
720
+ if (false !== apiResponse) {
721
+
722
+ responseCallback(response, request, apiResponse)
723
+
724
+ if (C6.GET === requestMethod) {
725
+
726
+ const responseData = response.data as iGetC6RestResponse<any>;
727
+
728
+ // @ts-ignore
729
+ returnGetNextPageFunction = 1 !== query?.[C6.PAGINATION]?.[C6.LIMIT] &&
730
+ query?.[C6.PAGINATION]?.[C6.LIMIT] === responseData.rest.length
731
+
732
+ if (false === isTest || true === isVerbose) {
733
+
734
+ console.groupCollapsed('%c API: Response returned length (' + responseData.rest?.length + ') of possible (' + query?.[C6.PAGINATION]?.[C6.LIMIT] + ') limit!', 'color: #0c0')
735
+
736
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0')
737
+
738
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', request)
739
+
740
+ console.log('%c Response Data:', 'color: #0c0', responseData.rest)
741
+
742
+ 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)
743
+
744
+ console.trace();
745
+
746
+ console.groupEnd()
747
+
748
+ }
749
+
750
+ if (false === returnGetNextPageFunction
751
+ && true === request.debug
752
+ && isLocal) {
753
+
754
+ toast.success("DEVS: Response returned length (" + responseData.rest?.length + ") less than limit (" + query?.[C6.PAGINATION]?.[C6.LIMIT] + ").", toastOptionsDevs);
755
+
756
+ }
757
+
758
+ }
759
+
760
+ }
761
+
762
+ if (cachingConfirmed) {
763
+
764
+ const cacheIndex = apiRequestCache.findIndex(cache => cache.requestArgumentsSerialized === querySerialized);
765
+
766
+ apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction
767
+
768
+ // only cache get method requests
769
+ apiRequestCache[cacheIndex].response = response
770
+
771
+ }
772
+
773
+ if (request.debug && isLocal) {
774
+
775
+ toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
776
+
777
+ }
778
+
779
+ return response;
780
+
781
+ });
782
+
783
+ } catch (error) {
784
+
785
+ if (isTest) {
786
+
787
+ throw new Error(JSON.stringify(error))
788
+
789
+ }
790
+
791
+ console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000')
792
+
793
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0')
794
+
795
+ console.warn(error)
796
+
797
+ console.trace()
798
+
799
+ console.groupEnd()
800
+
801
+ TestRestfulResponse(error, request?.success, request?.error || "An restful API error occurred!")
802
+
803
+ return null;
804
+
805
+ }
806
+
807
+
808
+ }
809
+
810
+ return apiRequest()
811
+
812
+ }
813
+
814
+ }
815
+