@carbonorm/carbonnode 1.0.0

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,604 @@
1
+ 'use strict';
2
+
3
+ var reactToastify = require('react-toastify');
4
+
5
+ const C6 = {
6
+ // try to 1=1 match the Rest abstract class
7
+ ADDDATE: 'ADDDATE',
8
+ ADDTIME: 'ADDTIME',
9
+ AS: 'AS',
10
+ ASC: 'ASC',
11
+ BETWEEN: 'BETWEEN',
12
+ CONCAT: 'CONCAT',
13
+ CONVERT_TZ: 'CONVERT_TZ',
14
+ COUNT: 'COUNT',
15
+ COUNT_ALL: 'COUNT_ALL',
16
+ CURRENT_DATE: 'CURRENT_DATE',
17
+ CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP',
18
+ DAY: 'DAY',
19
+ DAY_HOUR: 'DAY_HOUR',
20
+ DAY_MICROSECOND: 'DAY_MICROSECOND',
21
+ DAY_MINUTE: 'DAY_MINUTE',
22
+ DAY_SECOND: 'DAY_SECOND',
23
+ DAYNAME: 'DAYNAME',
24
+ DAYOFMONTH: 'DAYOFMONTH',
25
+ DAYOFWEEK: 'DAYOFWEEK',
26
+ DAYOFYEAR: 'DAYOFYEAR',
27
+ DATE: 'DATE',
28
+ DATE_ADD: 'DATE_ADD',
29
+ DATEDIFF: 'DATEDIFF',
30
+ DATE_SUB: 'DATE_SUB',
31
+ DATE_FORMAT: 'DATE_FORMAT',
32
+ DESC: 'DESC',
33
+ DISTINCT: 'DISTINCT',
34
+ EXTRACT: 'EXTRACT',
35
+ EQUAL: '=',
36
+ EQUAL_NULL_SAFE: '<=>',
37
+ FALSE: 'FALSE',
38
+ FULL_OUTER: 'FULL_OUTER',
39
+ FROM_DAYS: 'FROM_DAYS',
40
+ FROM_UNIXTIME: 'FROM_UNIXTIME',
41
+ GET_FORMAT: 'GET_FORMAT',
42
+ GREATER_THAN: '>',
43
+ GROUP_BY: 'GROUP_BY',
44
+ GROUP_CONCAT: 'GROUP_CONCAT',
45
+ GREATER_THAN_OR_EQUAL_TO: '>=',
46
+ HAVING: 'HAVING',
47
+ HEX: 'HEX',
48
+ HOUR: 'HOUR',
49
+ HOUR_MICROSECOND: 'HOUR_MICROSECOND',
50
+ HOUR_SECOND: 'HOUR_SECOND',
51
+ HOUR_MINUTE: 'HOUR_MINUTE',
52
+ IN: 'IN',
53
+ IS: 'IS',
54
+ IS_NOT: 'IS_NOT',
55
+ INNER: 'INNER',
56
+ INTERVAL: 'INTERVAL',
57
+ JOIN: 'JOIN',
58
+ LEFT: 'LEFT',
59
+ LEFT_OUTER: 'LEFT_OUTER',
60
+ LESS_THAN: '<',
61
+ LESS_THAN_OR_EQUAL_TO: '<=',
62
+ LIKE: 'LIKE',
63
+ LIMIT: 'LIMIT',
64
+ LOCALTIME: 'LOCALTIME',
65
+ LOCALTIMESTAMP: 'LOCALTIMESTAMP',
66
+ MAKEDATE: 'MAKEDATE',
67
+ MAKETIME: 'MAKETIME',
68
+ MONTHNAME: 'MONTHNAME',
69
+ MICROSECOND: 'MICROSECOND',
70
+ MINUTE: 'MINUTE',
71
+ MINUTE_MICROSECOND: 'MINUTE_MICROSECOND',
72
+ MINUTE_SECOND: 'MINUTE_SECOND',
73
+ MIN: 'MIN',
74
+ MAX: 'MAX',
75
+ MONTH: 'MONTH',
76
+ NOT_LIKE: 'NOT_LIKE',
77
+ NOT_EQUAL: '<>',
78
+ NOT_IN: 'NOT_IN',
79
+ NOW: 'NOW',
80
+ NULL: 'NULL',
81
+ ORDER: 'ORDER',
82
+ PAGE: 'PAGE',
83
+ PAGINATION: 'PAGINATION',
84
+ RIGHT_OUTER: 'RIGHT_OUTER',
85
+ SECOND: 'SECOND',
86
+ SECOND_MICROSECOND: 'SECOND_MICROSECOND',
87
+ SELECT: 'SELECT',
88
+ STR_TO_DATE: 'STR_TO_DATE',
89
+ SUBDATE: 'SUBDATE',
90
+ SUBTIME: 'SUBTIME',
91
+ SUM: 'SUM',
92
+ SYSDATE: 'SYSDATE',
93
+ TIME: 'TIME',
94
+ TIME_FORMAT: 'TIME_FORMAT',
95
+ TIME_TO_SEC: 'TIME_TO_SEC',
96
+ TIMEDIFF: 'TIMEDIFF',
97
+ TIMESTAMP: 'TIMESTAMP',
98
+ TIMESTAMPADD: 'TIMESTAMPADD',
99
+ TIMESTAMPDIFF: 'TIMESTAMPDIFF',
100
+ TO_DAYS: 'TO_DAYS',
101
+ TO_SECONDS: 'TO_SECONDS',
102
+ TRANSACTION_TIMESTAMP: 'TRANSACTION_TIMESTAMP',
103
+ TRUE: 'TRUE',
104
+ UNIX_TIMESTAMP: 'UNIX_TIMESTAMP',
105
+ UNKNOWN: 'UNKNOWN',
106
+ UPDATE: 'UPDATE',
107
+ UNHEX: 'UNHEX',
108
+ UTC_DATE: 'UNHEX',
109
+ UTC_TIME: 'UNHEX',
110
+ UTC_TIMESTAMP: 'UNHEX',
111
+ WHERE: 'WHERE',
112
+ WEEKDAY: 'WEEKDAY',
113
+ WEEKOFYEAR: 'WEEKOFYEAR',
114
+ YEARWEEK: 'YEARWEEK',
115
+ // carbon identifiers
116
+ DEPENDANT_ON_ENTITY: 'DEPENDANT_ON_ENTITY',
117
+ // PHP validation
118
+ OPTIONS: 'OPTIONS',
119
+ GET: 'GET',
120
+ POST: 'POST',
121
+ PUT: 'PUT',
122
+ REPLACE: 'REPLACE INTO',
123
+ DELETE: 'DELETE',
124
+ REST_REQUEST_PREPROCESS_CALLBACKS: 'PREPROCESS',
125
+ PREPROCESS: 'PREPROCESS',
126
+ REST_REQUEST_FINNISH_CALLBACKS: 'FINISH',
127
+ FINISH: 'FINISH',
128
+ VALIDATE_C6_ENTITY_ID_REGEX: '#^([a-fA-F0-9]{20,35})$#',
129
+ };
130
+
131
+ function convertForRequestBody (restfulObject, tableName, regexErrorHandler = alert) {
132
+ let payload = {};
133
+ const tableNames = Array.isArray(tableName) ? tableName : [tableName];
134
+ tableNames.forEach((table) => {
135
+ Object.keys(restfulObject).map(value => {
136
+ var _a;
137
+ let shortReference = value.toUpperCase();
138
+ switch (value) {
139
+ case C6.GET:
140
+ case C6.POST:
141
+ case C6.UPDATE:
142
+ case C6.REPLACE:
143
+ case C6.DELETE:
144
+ case C6.WHERE:
145
+ case C6.JOIN:
146
+ case C6.PAGINATION:
147
+ if (Array.isArray(restfulObject[value])) {
148
+ payload[value] = restfulObject[value].sort();
149
+ }
150
+ else if (typeof restfulObject[value] === 'object' && restfulObject[value] !== null) {
151
+ payload[value] = Object.keys(restfulObject[value])
152
+ .sort()
153
+ .reduce((acc, key) => (Object.assign(Object.assign({}, acc), { [key]: restfulObject[value][key] })), {});
154
+ }
155
+ return;
156
+ }
157
+ if (shortReference in C6[table]) {
158
+ const longName = C6[table][shortReference];
159
+ payload[longName] = restfulObject[value];
160
+ const regexValidations = C6[table].REGEX_VALIDATION[longName];
161
+ if (regexValidations instanceof RegExp) {
162
+ if (false === regexValidations.test(restfulObject[value])) {
163
+ regexErrorHandler('Failed to match regex (' + regexValidations + ') for column (' + longName + ')');
164
+ throw Error('Failed to match regex (' + regexValidations + ') for column (' + longName + ')');
165
+ }
166
+ }
167
+ else if (typeof regexValidations === 'object' && regexValidations !== null) {
168
+ (_a = Object.keys(regexValidations)) === null || _a === void 0 ? void 0 : _a.map((errorMessage) => {
169
+ const regex = regexValidations[errorMessage];
170
+ if (false === regex.test(restfulObject[value])) {
171
+ const devErrorMessage = 'Failed to match regex (' + regex + ') for column (' + longName + ')';
172
+ regexErrorHandler(errorMessage !== null && errorMessage !== void 0 ? errorMessage : devErrorMessage);
173
+ throw Error(devErrorMessage);
174
+ }
175
+ });
176
+ }
177
+ }
178
+ });
179
+ return true;
180
+ });
181
+ return Object.keys(payload)
182
+ .sort()
183
+ .reduce((acc, key) => (Object.assign(Object.assign({}, acc), { [key]: payload[key] })), {});
184
+ }
185
+
186
+ var isLocal = process.env.NODE_ENV === 'development';
187
+
188
+ const isTest = process.env.JEST_WORKER_ID !== undefined || process.env.NODE_ENV === 'test';
189
+
190
+ const isVerbose = process.env.REACT_APP_VERBOSE === 'true';
191
+
192
+ const toastOptions = {
193
+ position: "bottom-left",
194
+ autoClose: 10000,
195
+ hideProgressBar: false,
196
+ closeOnClick: true,
197
+ pauseOnHover: true,
198
+ draggable: true,
199
+ theme: "dark",
200
+ };
201
+ const toastOptionsDevs = {
202
+ position: "bottom-right",
203
+ autoClose: 3000,
204
+ hideProgressBar: false,
205
+ closeOnClick: true,
206
+ pauseOnHover: true,
207
+ draggable: true,
208
+ theme: "dark",
209
+ };
210
+
211
+ // todo - use bootstrap, it currently is prefixed with an underscore to denote to TS that we are aware it is unused.
212
+ // When we capture DropExceptions and display them as a custom page, this will change.
213
+ function TestRestfulResponse(response, success, error) {
214
+ var _a, _b, _c, _d, _e, _f, _g, _h;
215
+ if (undefined === ((_a = response.data) === null || _a === void 0 ? void 0 : _a['ERROR TYPE'])
216
+ && (undefined !== ((_b = response === null || response === void 0 ? void 0 : response.data) === null || _b === void 0 ? void 0 : _b.rest)
217
+ || undefined !== ((_c = response.data) === null || _c === void 0 ? void 0 : _c.created)
218
+ || undefined !== ((_d = response.data) === null || _d === void 0 ? void 0 : _d.updated)
219
+ || undefined !== ((_e = response.data) === null || _e === void 0 ? void 0 : _e.deleted))) {
220
+ let successReturn = 'function' === typeof success ? success === null || success === void 0 ? void 0 : success(response) : success;
221
+ if (typeof successReturn === 'string') {
222
+ reactToastify.toast.success(successReturn, toastOptions);
223
+ }
224
+ // this could end up with bad results for deleting id's === 0
225
+ return (_h = (_g = (_f = response.data.created) !== null && _f !== void 0 ? _f : response.data.updated) !== null && _g !== void 0 ? _g : response.data.deleted) !== null && _h !== void 0 ? _h : true;
226
+ }
227
+ let errorReturn = 'function' === typeof error ? error === null || error === void 0 ? void 0 : error(response) : error;
228
+ if (typeof errorReturn === 'string') {
229
+ reactToastify.toast.error(errorReturn, toastOptions);
230
+ }
231
+ return false;
232
+ }
233
+ function removeInvalidKeys(request, c6Tables) {
234
+ let intersection = {};
235
+ let restfulObjectKeys = [];
236
+ c6Tables.forEach(table => Object.values(table.COLUMNS).forEach(column => {
237
+ if (false === restfulObjectKeys.includes(column)) {
238
+ restfulObjectKeys.push(column);
239
+ }
240
+ }));
241
+ Object.keys(request).forEach(key => {
242
+ if (restfulObjectKeys.includes(key)) {
243
+ intersection[key] = request[key];
244
+ }
245
+ });
246
+ isTest || console.log('intersection', intersection);
247
+ return intersection;
248
+ }
249
+ // do not remove entries from this array. It is used to track the progress of API requests.
250
+ // position in array is important. Do not sort. To not add to begging.
251
+ let apiRequestCache = [];
252
+ let userCustomClearCache = [];
253
+ function checkAllRequestsComplete() {
254
+ const stillRunning = apiRequestCache.filter((cache) => undefined === cache.response);
255
+ if (stillRunning.length !== 0) {
256
+ if (document === null || document === undefined) {
257
+ throw new Error('document is undefined while waiting for API requests to complete (' + JSON.stringify(apiRequestCache) + ')');
258
+ }
259
+ // when requests return emtpy sets in full renders, it may not be possible to track their progress.
260
+ console.warn('stillRunning...', stillRunning);
261
+ return stillRunning.map((cache) => cache.requestArgumentsSerialized);
262
+ }
263
+ return true;
264
+ }
265
+ function checkCache(cacheResult, requestMethod, tableName, request) {
266
+ var _a, _b, _c;
267
+ if (undefined === (cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.response)) {
268
+ 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');
269
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
270
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', request);
271
+ console.groupEnd();
272
+ return cacheResult.request;
273
+ }
274
+ if (true === (cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.final)) {
275
+ if (false === isTest || true === isVerbose) {
276
+ console.groupCollapsed('%c API: rest api cache has reached the final result. Returning undefined!', 'color: #cc0');
277
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #cc0');
278
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #cc0', request);
279
+ console.log('%c Response Data:', 'color: #cc0', ((_b = (_a = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.rest) || ((_c = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.response) === null || _c === void 0 ? void 0 : _c.data) || (cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.response));
280
+ console.groupEnd();
281
+ }
282
+ return undefined;
283
+ }
284
+ return false;
285
+ }
286
+ function sortAndSerializeQueryObject(tables, query) {
287
+ const orderedQuery = Object.keys(query).sort().reduce((obj, key) => {
288
+ obj[key] = query[key];
289
+ return obj;
290
+ }, {});
291
+ return tables + ' ' + JSON.stringify(orderedQuery);
292
+ }
293
+ function clearCache(props) {
294
+ if (false === (props === null || props === void 0 ? void 0 : props.ignoreWarning)) {
295
+ console.warn('The rest api clearCache should only be used with extreme care! Avoid using this in favor of using `cacheResults : boolean`.');
296
+ }
297
+ userCustomClearCache.map((f) => 'function' === typeof f && f());
298
+ userCustomClearCache = apiRequestCache = [];
299
+ }
300
+ /**
301
+ * the first argument ....
302
+ *
303
+ * Our api returns a zero argument function iff the method is get and the previous request reached the predefined limit.
304
+ * This function can be aliased as GetNextPageOfResults(). If the end is reached undefined will be returned.
305
+ *
306
+ *
307
+ * For POST, PUT, and DELETE requests one can expect the primary key of the new or modified index, or a boolean success
308
+ * indication if no primary key exists.
309
+ **/
310
+ const POST = 'POST';
311
+ const PUT = 'PUT';
312
+ const GET = 'GET';
313
+ const DELETE = 'DELETE';
314
+ function isPromise(x) {
315
+ return Object(x).constructor === Promise;
316
+ }
317
+ function extendedTypeHints() {
318
+ return (argv) => restApi(argv);
319
+ }
320
+ function restApi({ C6, axios, restURL, tableName, requestMethod = GET, queryCallback = {}, responseCallback, skipPrimaryCheck = false, clearCache = undefined }) {
321
+ const fullTableList = Array.isArray(tableName) ? tableName : [tableName];
322
+ const operatingTable = fullTableList[0];
323
+ const tables = fullTableList.join(',');
324
+ switch (requestMethod) {
325
+ case GET:
326
+ case POST:
327
+ case PUT:
328
+ case DELETE:
329
+ break;
330
+ default:
331
+ throw Error('Bad request method passed to getApi');
332
+ }
333
+ if (null !== clearCache || undefined !== clearCache) {
334
+ userCustomClearCache[tables + requestMethod] = clearCache;
335
+ }
336
+ return (request = {}) => {
337
+ // an undefined query would indicate queryCallback returned undefined,
338
+ // thus the request shouldn't fire as is in custom cache
339
+ let query;
340
+ if ('function' === typeof queryCallback) {
341
+ query = queryCallback(request); // obj or obj[]
342
+ }
343
+ else {
344
+ query = queryCallback;
345
+ }
346
+ if (undefined === query || null === query) {
347
+ if (request.debug && isLocal) {
348
+ reactToastify.toast.warning("DEV: queryCallback returned undefined, signaling in Custom Cache. (returning null)", toastOptionsDevs);
349
+ }
350
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') undefined, returning null (will not fire ajax)!', 'color: #c00');
351
+ 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');
352
+ console.trace();
353
+ console.groupEnd();
354
+ return null;
355
+ }
356
+ if (C6.GET === requestMethod) {
357
+ if (undefined === query[C6.PAGINATION]) {
358
+ query[C6.PAGINATION] = {};
359
+ }
360
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
361
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
362
+ }
363
+ // this could return itself with a new page number, or undefined if the end is reached
364
+ function apiRequest() {
365
+ var _a, _b, _c, _d, _e, _f, _g;
366
+ (_a = request.cacheResults) !== null && _a !== void 0 ? _a : (request.cacheResults = C6.GET === requestMethod);
367
+ if (C6.GET === requestMethod
368
+ && undefined !== ((_b = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _b === void 0 ? void 0 : _b[C6.PAGE])
369
+ && 1 !== query[C6.PAGINATION][C6.PAGE]) {
370
+ console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
371
+ console.log('Request Data (note you may see the success and/or error prompt):', request);
372
+ console.trace();
373
+ console.groupEnd();
374
+ }
375
+ // 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.
376
+ // 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
377
+ // literally impossible for query to be undefined or null here but the editor is too busy licking windows to understand that
378
+ let querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
379
+ let cacheResult = apiRequestCache.find(cache => cache.requestArgumentsSerialized === querySerialized);
380
+ let cachingConfirmed = false;
381
+ // determine if we need to paginate.
382
+ if (requestMethod === C6.GET) {
383
+ if (undefined === (query === null || query === void 0 ? void 0 : query[C6.PAGINATION])) {
384
+ if (undefined === query || null === query) {
385
+ query = {};
386
+ }
387
+ query[C6.PAGINATION] = {};
388
+ }
389
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
390
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
391
+ // this will evaluate true most the time
392
+ if (true === request.cacheResults) {
393
+ // just find the next, non-fetched, page and return a function to request it
394
+ if (undefined !== cacheResult) {
395
+ do {
396
+ const cacheCheck = checkCache(cacheResult, requestMethod, tableName, request);
397
+ if (false !== cacheCheck) {
398
+ return cacheCheck;
399
+ }
400
+ // this line incrementing page is why we return recursively
401
+ ++query[C6.PAGINATION][C6.PAGE];
402
+ // this json stringify is to capture the new page number
403
+ querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
404
+ cacheResult = apiRequestCache.find(cache => cache.requestArgumentsSerialized === querySerialized);
405
+ } while (undefined !== cacheResult);
406
+ if (request.debug && isLocal) {
407
+ reactToastify.toast.warning("DEVS: Request in cache. (" + apiRequestCache.findIndex(cache => cache.requestArgumentsSerialized === querySerialized) + "). Returning function to request page (" + query[C6.PAGINATION][C6.PAGE] + ")", toastOptionsDevs);
408
+ }
409
+ // @ts-ignore - this is an incorrect warning on TS, it's well typed
410
+ return apiRequest;
411
+ }
412
+ cachingConfirmed = true;
413
+ }
414
+ else {
415
+ if (request.debug && isLocal) {
416
+ reactToastify.toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
417
+ }
418
+ }
419
+ if (request.debug && isLocal) {
420
+ reactToastify.toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
421
+ }
422
+ }
423
+ else if (request.cacheResults) { // if we are not getting, we are updating, deleting, or inserting
424
+ if (cacheResult) {
425
+ const cacheCheck = checkCache(cacheResult, requestMethod, tableName, request);
426
+ if (false !== cacheCheck) {
427
+ return cacheCheck;
428
+ }
429
+ }
430
+ cachingConfirmed = true;
431
+ // push to cache so we do not repeat the request
432
+ }
433
+ let addBackPK;
434
+ let apiResponse;
435
+ let returnGetNextPageFunction = false;
436
+ let restRequestUri = restURL + operatingTable + '/';
437
+ const needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
438
+ && false === skipPrimaryCheck;
439
+ const TABLES = C6.TABLES;
440
+ // todo - aggregate primary key check with condition check
441
+ // check if PK exists in query, clone so pop does not affect the real data
442
+ const primaryKey = (_f = (_e = (_d = structuredClone((_c = TABLES[operatingTable]) === null || _c === void 0 ? void 0 : _c.PRIMARY)) === null || _d === void 0 ? void 0 : _d.pop()) === null || _e === void 0 ? void 0 : _e.split('.')) === null || _f === void 0 ? void 0 : _f.pop();
443
+ if (needsConditionOrPrimaryCheck) {
444
+ if (undefined === primaryKey) {
445
+ if (null === query
446
+ || undefined === query
447
+ || undefined === (query === null || query === void 0 ? void 0 : query[C6.WHERE])
448
+ || (true === Array.isArray(query[C6.WHERE])
449
+ || query[C6.WHERE].length === 0)
450
+ || (Object.keys(query === null || query === void 0 ? void 0 : query[C6.WHERE]).length === 0)) {
451
+ console.error(query);
452
+ throw Error('Failed to parse primary key information(' + JSON.stringify(query) + JSON.stringify(primaryKey) + ')' + JSON.stringify((_g = TABLES[operatingTable]) === null || _g === void 0 ? void 0 : _g.PRIMARY) + ' for table (' + operatingTable + ').');
453
+ }
454
+ }
455
+ else {
456
+ if (undefined === query
457
+ || null === query
458
+ || false === primaryKey in query) {
459
+ if (true === request.debug && isLocal) {
460
+ reactToastify.toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
461
+ }
462
+ throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
463
+ }
464
+ if (undefined === (query === null || query === void 0 ? void 0 : query[primaryKey])
465
+ || null === (query === null || query === void 0 ? void 0 : query[primaryKey])) {
466
+ reactToastify.toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!');
467
+ throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
468
+ }
469
+ }
470
+ }
471
+ // todo - remove
472
+ if (undefined !== query
473
+ && null !== query
474
+ && undefined !== primaryKey
475
+ && primaryKey in query) {
476
+ restRequestUri += query[primaryKey] + '/';
477
+ const removedPkValue = query[primaryKey];
478
+ addBackPK = () => {
479
+ query !== null && query !== void 0 ? query : (query = {});
480
+ query[primaryKey] = removedPkValue;
481
+ };
482
+ delete query[primaryKey];
483
+ }
484
+ try {
485
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
486
+ console.log(request);
487
+ 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');
488
+ 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');
489
+ console.trace();
490
+ console.groupEnd();
491
+ const axiosActiveRequest = axios[requestMethod.toLowerCase()](restRequestUri, (() => {
492
+ // we had removed the value from the request to add to the URI.
493
+ addBackPK === null || addBackPK === void 0 ? void 0 : addBackPK(); // adding back so post-processing methods work
494
+ if (requestMethod === GET) {
495
+ return {
496
+ params: query
497
+ };
498
+ }
499
+ else if (requestMethod === POST) {
500
+ if (undefined !== (request === null || request === void 0 ? void 0 : request.dataInsertMultipleRows)) {
501
+ return request.dataInsertMultipleRows.map(data => convertForRequestBody(data, fullTableList, (message) => reactToastify.toast.error(message, toastOptions)));
502
+ }
503
+ return convertForRequestBody(query, fullTableList, (message) => reactToastify.toast.error(message, toastOptions));
504
+ }
505
+ else if (requestMethod === PUT) {
506
+ return convertForRequestBody(query, fullTableList, (message) => reactToastify.toast.error(message, toastOptions));
507
+ }
508
+ else if (requestMethod === DELETE) {
509
+ return {
510
+ data: convertForRequestBody(query, fullTableList, (message) => reactToastify.toast.error(message, toastOptions))
511
+ };
512
+ }
513
+ else {
514
+ throw new Error('The request method (' + requestMethod + ') was not recognized.');
515
+ }
516
+ })());
517
+ if (cachingConfirmed) {
518
+ // push to cache so we do not repeat the request
519
+ apiRequestCache.push({
520
+ requestArgumentsSerialized: querySerialized,
521
+ request: axiosActiveRequest
522
+ });
523
+ }
524
+ // https://rapidapi.com/guides/axios-async-await
525
+ return axiosActiveRequest.then(response => {
526
+ var _a, _b, _c, _d, _e, _f, _g, _h;
527
+ if (typeof response.data === 'string') {
528
+ if (isTest) {
529
+ console.trace();
530
+ 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 + ')');
531
+ }
532
+ return Promise.reject(response);
533
+ }
534
+ apiResponse = TestRestfulResponse(response, request === null || request === void 0 ? void 0 : request.success, (_a = request === null || request === void 0 ? void 0 : request.error) !== null && _a !== void 0 ? _a : "An unexpected API error occurred!");
535
+ if (false !== apiResponse) {
536
+ responseCallback(response, request, apiResponse);
537
+ if (C6.GET === requestMethod) {
538
+ const responseData = response.data;
539
+ // @ts-ignore
540
+ returnGetNextPageFunction = 1 !== ((_b = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _b === void 0 ? void 0 : _b[C6.LIMIT]) &&
541
+ ((_c = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _c === void 0 ? void 0 : _c[C6.LIMIT]) === responseData.rest.length;
542
+ if (false === isTest || true === isVerbose) {
543
+ console.groupCollapsed('%c API: Response returned length (' + ((_d = responseData.rest) === null || _d === void 0 ? void 0 : _d.length) + ') of possible (' + ((_e = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _e === void 0 ? void 0 : _e[C6.LIMIT]) + ') limit!', 'color: #0c0');
544
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
545
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', request);
546
+ console.log('%c Response Data:', 'color: #0c0', responseData.rest);
547
+ console.log('%c Will return get next page function:' + (1 !== ((_f = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _f === void 0 ? void 0 : _f[C6.LIMIT]) ? '' : ' (Will not return with explicit limit 1 set)'), 'color: #0c0', true === returnGetNextPageFunction);
548
+ console.trace();
549
+ console.groupEnd();
550
+ }
551
+ if (false === returnGetNextPageFunction
552
+ && true === request.debug
553
+ && isLocal) {
554
+ reactToastify.toast.success("DEVS: Response returned length (" + ((_g = responseData.rest) === null || _g === void 0 ? void 0 : _g.length) + ") less than limit (" + ((_h = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _h === void 0 ? void 0 : _h[C6.LIMIT]) + ").", toastOptionsDevs);
555
+ }
556
+ }
557
+ }
558
+ if (cachingConfirmed) {
559
+ const cacheIndex = apiRequestCache.findIndex(cache => cache.requestArgumentsSerialized === querySerialized);
560
+ apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction;
561
+ // only cache get method requests
562
+ apiRequestCache[cacheIndex].response = response;
563
+ }
564
+ if (request.debug && isLocal) {
565
+ reactToastify.toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
566
+ }
567
+ return response;
568
+ });
569
+ }
570
+ catch (error) {
571
+ if (isTest) {
572
+ throw new Error(JSON.stringify(error));
573
+ }
574
+ console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
575
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
576
+ console.warn(error);
577
+ console.trace();
578
+ console.groupEnd();
579
+ TestRestfulResponse(error, request === null || request === void 0 ? void 0 : request.success, (request === null || request === void 0 ? void 0 : request.error) || "An restful API error occurred!");
580
+ return null;
581
+ }
582
+ }
583
+ return apiRequest();
584
+ };
585
+ }
586
+
587
+ exports.C6 = C6;
588
+ exports.DELETE = DELETE;
589
+ exports.GET = GET;
590
+ exports.POST = POST;
591
+ exports.PUT = PUT;
592
+ exports.TestRestfulResponse = TestRestfulResponse;
593
+ exports.checkAllRequestsComplete = checkAllRequestsComplete;
594
+ exports.clearCache = clearCache;
595
+ exports.convertForRequestBody = convertForRequestBody;
596
+ exports.extendedTypeHints = extendedTypeHints;
597
+ exports.isLocal = isLocal;
598
+ exports.isPromise = isPromise;
599
+ exports.isTest = isTest;
600
+ exports.isVerbose = isVerbose;
601
+ exports.removeInvalidKeys = removeInvalidKeys;
602
+ exports.restRequest = restApi;
603
+ exports.toastOptions = toastOptions;
604
+ exports.toastOptionsDevs = toastOptionsDevs;