@carbonorm/carbonnode 1.0.0 → 1.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.
@@ -0,0 +1,649 @@
1
+ 'use strict';
2
+
3
+ var reactToastify = require('react-toastify');
4
+
5
+ var 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
+ /******************************************************************************
132
+ Copyright (c) Microsoft Corporation.
133
+
134
+ Permission to use, copy, modify, and/or distribute this software for any
135
+ purpose with or without fee is hereby granted.
136
+
137
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
138
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
139
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
140
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
141
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
142
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
143
+ PERFORMANCE OF THIS SOFTWARE.
144
+ ***************************************************************************** */
145
+ /* global Reflect, Promise, SuppressedError, Symbol */
146
+
147
+
148
+ var __assign = function() {
149
+ __assign = Object.assign || function __assign(t) {
150
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
151
+ s = arguments[i];
152
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
153
+ }
154
+ return t;
155
+ };
156
+ return __assign.apply(this, arguments);
157
+ };
158
+
159
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
160
+ var e = new Error(message);
161
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
162
+ };
163
+
164
+ function convertForRequestBody (restfulObject, tableName, regexErrorHandler) {
165
+ if (regexErrorHandler === void 0) { regexErrorHandler = alert; }
166
+ var payload = {};
167
+ var tableNames = Array.isArray(tableName) ? tableName : [tableName];
168
+ tableNames.forEach(function (table) {
169
+ Object.keys(restfulObject).map(function (value) {
170
+ var _a;
171
+ var shortReference = value.toUpperCase();
172
+ switch (value) {
173
+ case C6.GET:
174
+ case C6.POST:
175
+ case C6.UPDATE:
176
+ case C6.REPLACE:
177
+ case C6.DELETE:
178
+ case C6.WHERE:
179
+ case C6.JOIN:
180
+ case C6.PAGINATION:
181
+ if (Array.isArray(restfulObject[value])) {
182
+ payload[value] = restfulObject[value].sort();
183
+ }
184
+ else if (typeof restfulObject[value] === 'object' && restfulObject[value] !== null) {
185
+ payload[value] = Object.keys(restfulObject[value])
186
+ .sort()
187
+ .reduce(function (acc, key) {
188
+ var _a;
189
+ return (__assign(__assign({}, acc), (_a = {}, _a[key] = restfulObject[value][key], _a)));
190
+ }, {});
191
+ }
192
+ return;
193
+ }
194
+ if (shortReference in C6[table]) {
195
+ var longName_1 = C6[table][shortReference];
196
+ payload[longName_1] = restfulObject[value];
197
+ var regexValidations_1 = C6[table].REGEX_VALIDATION[longName_1];
198
+ if (regexValidations_1 instanceof RegExp) {
199
+ if (false === regexValidations_1.test(restfulObject[value])) {
200
+ regexErrorHandler('Failed to match regex (' + regexValidations_1 + ') for column (' + longName_1 + ')');
201
+ throw Error('Failed to match regex (' + regexValidations_1 + ') for column (' + longName_1 + ')');
202
+ }
203
+ }
204
+ else if (typeof regexValidations_1 === 'object' && regexValidations_1 !== null) {
205
+ (_a = Object.keys(regexValidations_1)) === null || _a === void 0 ? void 0 : _a.map(function (errorMessage) {
206
+ var regex = regexValidations_1[errorMessage];
207
+ if (false === regex.test(restfulObject[value])) {
208
+ var devErrorMessage = 'Failed to match regex (' + regex + ') for column (' + longName_1 + ')';
209
+ regexErrorHandler(errorMessage !== null && errorMessage !== void 0 ? errorMessage : devErrorMessage);
210
+ throw Error(devErrorMessage);
211
+ }
212
+ });
213
+ }
214
+ }
215
+ });
216
+ return true;
217
+ });
218
+ return Object.keys(payload)
219
+ .sort()
220
+ .reduce(function (acc, key) {
221
+ var _a;
222
+ return (__assign(__assign({}, acc), (_a = {}, _a[key] = payload[key], _a)));
223
+ }, {});
224
+ }
225
+
226
+ var isLocal = process.env.NODE_ENV === 'development';
227
+
228
+ var isTest = process.env.JEST_WORKER_ID !== undefined || process.env.NODE_ENV === 'test';
229
+
230
+ var isVerbose = process.env.REACT_APP_VERBOSE === 'true';
231
+
232
+ var toastOptions = {
233
+ position: "bottom-left",
234
+ autoClose: 10000,
235
+ hideProgressBar: false,
236
+ closeOnClick: true,
237
+ pauseOnHover: true,
238
+ draggable: true,
239
+ theme: "dark",
240
+ };
241
+ var toastOptionsDevs = {
242
+ position: "bottom-right",
243
+ autoClose: 3000,
244
+ hideProgressBar: false,
245
+ closeOnClick: true,
246
+ pauseOnHover: true,
247
+ draggable: true,
248
+ theme: "dark",
249
+ };
250
+
251
+ // todo - use bootstrap, it currently is prefixed with an underscore to denote to TS that we are aware it is unused.
252
+ // When we capture DropExceptions and display them as a custom page, this will change.
253
+ function TestRestfulResponse(response, success, error) {
254
+ var _a, _b, _c, _d, _e, _f, _g, _h;
255
+ if (undefined === ((_a = response.data) === null || _a === void 0 ? void 0 : _a['ERROR TYPE'])
256
+ && (undefined !== ((_b = response === null || response === void 0 ? void 0 : response.data) === null || _b === void 0 ? void 0 : _b.rest)
257
+ || undefined !== ((_c = response.data) === null || _c === void 0 ? void 0 : _c.created)
258
+ || undefined !== ((_d = response.data) === null || _d === void 0 ? void 0 : _d.updated)
259
+ || undefined !== ((_e = response.data) === null || _e === void 0 ? void 0 : _e.deleted))) {
260
+ var successReturn = 'function' === typeof success ? success === null || success === void 0 ? void 0 : success(response) : success;
261
+ if (typeof successReturn === 'string') {
262
+ reactToastify.toast.success(successReturn, toastOptions);
263
+ }
264
+ // this could end up with bad results for deleting id's === 0
265
+ 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;
266
+ }
267
+ var errorReturn = 'function' === typeof error ? error === null || error === void 0 ? void 0 : error(response) : error;
268
+ if (typeof errorReturn === 'string') {
269
+ reactToastify.toast.error(errorReturn, toastOptions);
270
+ }
271
+ return false;
272
+ }
273
+ function removeInvalidKeys(request, c6Tables) {
274
+ var intersection = {};
275
+ var restfulObjectKeys = [];
276
+ c6Tables.forEach(function (table) { return Object.values(table.COLUMNS).forEach(function (column) {
277
+ if (false === restfulObjectKeys.includes(column)) {
278
+ restfulObjectKeys.push(column);
279
+ }
280
+ }); });
281
+ Object.keys(request).forEach(function (key) {
282
+ if (restfulObjectKeys.includes(key)) {
283
+ intersection[key] = request[key];
284
+ }
285
+ });
286
+ isTest || console.log('intersection', intersection);
287
+ return intersection;
288
+ }
289
+ // do not remove entries from this array. It is used to track the progress of API requests.
290
+ // position in array is important. Do not sort. To not add to begging.
291
+ var apiRequestCache = [];
292
+ var userCustomClearCache = [];
293
+ function checkAllRequestsComplete() {
294
+ var stillRunning = apiRequestCache.filter(function (cache) { return undefined === cache.response; });
295
+ if (stillRunning.length !== 0) {
296
+ if (document === null || document === undefined) {
297
+ throw new Error('document is undefined while waiting for API requests to complete (' + JSON.stringify(apiRequestCache) + ')');
298
+ }
299
+ // when requests return emtpy sets in full renders, it may not be possible to track their progress.
300
+ console.warn('stillRunning...', stillRunning);
301
+ return stillRunning.map(function (cache) { return cache.requestArgumentsSerialized; });
302
+ }
303
+ return true;
304
+ }
305
+ function checkCache(cacheResult, requestMethod, tableName, request) {
306
+ var _a, _b, _c;
307
+ if (undefined === (cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.response)) {
308
+ 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');
309
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
310
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', request);
311
+ console.groupEnd();
312
+ return cacheResult.request;
313
+ }
314
+ if (true === (cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.final)) {
315
+ if (false === isTest || true === isVerbose) {
316
+ console.groupCollapsed('%c API: rest api cache has reached the final result. Returning undefined!', 'color: #cc0');
317
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #cc0');
318
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #cc0', request);
319
+ 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));
320
+ console.groupEnd();
321
+ }
322
+ return undefined;
323
+ }
324
+ return false;
325
+ }
326
+ function sortAndSerializeQueryObject(tables, query) {
327
+ var orderedQuery = Object.keys(query).sort().reduce(function (obj, key) {
328
+ obj[key] = query[key];
329
+ return obj;
330
+ }, {});
331
+ return tables + ' ' + JSON.stringify(orderedQuery);
332
+ }
333
+ function clearCache(props) {
334
+ if (false === (props === null || props === void 0 ? void 0 : props.ignoreWarning)) {
335
+ console.warn('The rest api clearCache should only be used with extreme care! Avoid using this in favor of using `cacheResults : boolean`.');
336
+ }
337
+ userCustomClearCache.map(function (f) { return 'function' === typeof f && f(); });
338
+ userCustomClearCache = apiRequestCache = [];
339
+ }
340
+ /**
341
+ * the first argument ....
342
+ *
343
+ * Our api returns a zero argument function iff the method is get and the previous request reached the predefined limit.
344
+ * This function can be aliased as GetNextPageOfResults(). If the end is reached undefined will be returned.
345
+ *
346
+ *
347
+ * For POST, PUT, and DELETE requests one can expect the primary key of the new or modified index, or a boolean success
348
+ * indication if no primary key exists.
349
+ **/
350
+ var POST = 'POST';
351
+ var PUT = 'PUT';
352
+ var GET = 'GET';
353
+ var DELETE = 'DELETE';
354
+ function isPromise(x) {
355
+ return Object(x).constructor === Promise;
356
+ }
357
+ function extendedTypeHints() {
358
+ return function (argv) { return restApi(argv); };
359
+ }
360
+ function restApi(_a) {
361
+ var C6 = _a.C6, axios = _a.axios, restURL = _a.restURL, tableName = _a.tableName, _b = _a.requestMethod, requestMethod = _b === void 0 ? GET : _b, _c = _a.queryCallback, queryCallback = _c === void 0 ? {} : _c, responseCallback = _a.responseCallback, _d = _a.skipPrimaryCheck, skipPrimaryCheck = _d === void 0 ? false : _d, _e = _a.clearCache, clearCache = _e === void 0 ? undefined : _e;
362
+ var fullTableList = Array.isArray(tableName) ? tableName : [tableName];
363
+ var operatingTable = fullTableList[0];
364
+ var tables = fullTableList.join(',');
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
+ if (null !== clearCache || undefined !== clearCache) {
375
+ userCustomClearCache[tables + requestMethod] = clearCache;
376
+ }
377
+ return function (request) {
378
+ if (request === void 0) { request = {}; }
379
+ // an undefined query would indicate queryCallback returned undefined,
380
+ // thus the request shouldn't fire as is in custom cache
381
+ var query;
382
+ if ('function' === typeof queryCallback) {
383
+ query = queryCallback(request); // obj or obj[]
384
+ }
385
+ else {
386
+ query = queryCallback;
387
+ }
388
+ if (undefined === query || null === query) {
389
+ if (request.debug && isLocal) {
390
+ reactToastify.toast.warning("DEV: queryCallback returned undefined, signaling in Custom Cache. (returning null)", toastOptionsDevs);
391
+ }
392
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') undefined, returning null (will not fire ajax)!', 'color: #c00');
393
+ 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');
394
+ console.trace();
395
+ console.groupEnd();
396
+ return null;
397
+ }
398
+ if (C6.GET === requestMethod) {
399
+ if (undefined === query[C6.PAGINATION]) {
400
+ query[C6.PAGINATION] = {};
401
+ }
402
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
403
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
404
+ }
405
+ // this could return itself with a new page number, or undefined if the end is reached
406
+ function apiRequest() {
407
+ var _a, _b, _c, _d, _e, _f, _g;
408
+ (_a = request.cacheResults) !== null && _a !== void 0 ? _a : (request.cacheResults = C6.GET === requestMethod);
409
+ if (C6.GET === requestMethod
410
+ && undefined !== ((_b = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _b === void 0 ? void 0 : _b[C6.PAGE])
411
+ && 1 !== query[C6.PAGINATION][C6.PAGE]) {
412
+ console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
413
+ console.log('Request Data (note you may see the success and/or error prompt):', request);
414
+ console.trace();
415
+ console.groupEnd();
416
+ }
417
+ // 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.
418
+ // 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
419
+ // literally impossible for query to be undefined or null here but the editor is too busy licking windows to understand that
420
+ var querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
421
+ var cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
422
+ var cachingConfirmed = false;
423
+ // determine if we need to paginate.
424
+ if (requestMethod === C6.GET) {
425
+ if (undefined === (query === null || query === void 0 ? void 0 : query[C6.PAGINATION])) {
426
+ if (undefined === query || null === query) {
427
+ query = {};
428
+ }
429
+ query[C6.PAGINATION] = {};
430
+ }
431
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
432
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
433
+ // this will evaluate true most the time
434
+ if (true === request.cacheResults) {
435
+ // just find the next, non-fetched, page and return a function to request it
436
+ if (undefined !== cacheResult) {
437
+ do {
438
+ var cacheCheck = checkCache(cacheResult, requestMethod, tableName, request);
439
+ if (false !== cacheCheck) {
440
+ return cacheCheck;
441
+ }
442
+ // this line incrementing page is why we return recursively
443
+ ++query[C6.PAGINATION][C6.PAGE];
444
+ // this json stringify is to capture the new page number
445
+ querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
446
+ cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
447
+ } while (undefined !== cacheResult);
448
+ if (request.debug && isLocal) {
449
+ reactToastify.toast.warning("DEVS: Request in cache. (" + apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; }) + "). Returning function to request page (" + query[C6.PAGINATION][C6.PAGE] + ")", toastOptionsDevs);
450
+ }
451
+ // @ts-ignore - this is an incorrect warning on TS, it's well typed
452
+ return apiRequest;
453
+ }
454
+ cachingConfirmed = true;
455
+ }
456
+ else {
457
+ if (request.debug && isLocal) {
458
+ reactToastify.toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
459
+ }
460
+ }
461
+ if (request.debug && isLocal) {
462
+ reactToastify.toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
463
+ }
464
+ }
465
+ else if (request.cacheResults) { // if we are not getting, we are updating, deleting, or inserting
466
+ if (cacheResult) {
467
+ var cacheCheck = checkCache(cacheResult, requestMethod, tableName, request);
468
+ if (false !== cacheCheck) {
469
+ return cacheCheck;
470
+ }
471
+ }
472
+ cachingConfirmed = true;
473
+ // push to cache so we do not repeat the request
474
+ }
475
+ var addBackPK;
476
+ var apiResponse;
477
+ var returnGetNextPageFunction = false;
478
+ var restRequestUri = restURL + operatingTable + '/';
479
+ var needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
480
+ && false === skipPrimaryCheck;
481
+ var TABLES = C6.TABLES;
482
+ // todo - aggregate primary key check with condition check
483
+ // check if PK exists in query, clone so pop does not affect the real data
484
+ var 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();
485
+ if (needsConditionOrPrimaryCheck) {
486
+ if (undefined === primaryKey) {
487
+ if (null === query
488
+ || undefined === query
489
+ || undefined === (query === null || query === void 0 ? void 0 : query[C6.WHERE])
490
+ || (true === Array.isArray(query[C6.WHERE])
491
+ || query[C6.WHERE].length === 0)
492
+ || (Object.keys(query === null || query === void 0 ? void 0 : query[C6.WHERE]).length === 0)) {
493
+ console.error(query);
494
+ 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 + ').');
495
+ }
496
+ }
497
+ else {
498
+ if (undefined === query
499
+ || null === query
500
+ || false === primaryKey in query) {
501
+ if (true === request.debug && isLocal) {
502
+ reactToastify.toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
503
+ }
504
+ throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
505
+ }
506
+ if (undefined === (query === null || query === void 0 ? void 0 : query[primaryKey])
507
+ || null === (query === null || query === void 0 ? void 0 : query[primaryKey])) {
508
+ reactToastify.toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!');
509
+ throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
510
+ }
511
+ }
512
+ }
513
+ // todo - remove
514
+ if (undefined !== query
515
+ && null !== query
516
+ && undefined !== primaryKey
517
+ && primaryKey in query) {
518
+ restRequestUri += query[primaryKey] + '/';
519
+ var removedPkValue_1 = query[primaryKey];
520
+ addBackPK = function () {
521
+ query !== null && query !== void 0 ? query : (query = {});
522
+ query[primaryKey] = removedPkValue_1;
523
+ };
524
+ delete query[primaryKey];
525
+ }
526
+ try {
527
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
528
+ console.log(request);
529
+ 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');
530
+ 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');
531
+ console.trace();
532
+ console.groupEnd();
533
+ var axiosActiveRequest = axios[requestMethod.toLowerCase()](restRequestUri, (function () {
534
+ // we had removed the value from the request to add to the URI.
535
+ addBackPK === null || addBackPK === void 0 ? void 0 : addBackPK(); // adding back so post-processing methods work
536
+ if (requestMethod === GET) {
537
+ return {
538
+ params: query
539
+ };
540
+ }
541
+ else if (requestMethod === POST) {
542
+ if (undefined !== (request === null || request === void 0 ? void 0 : request.dataInsertMultipleRows)) {
543
+ return request.dataInsertMultipleRows.map(function (data) {
544
+ return convertForRequestBody(data, fullTableList, function (message) { return reactToastify.toast.error(message, toastOptions); });
545
+ });
546
+ }
547
+ return convertForRequestBody(query, fullTableList, function (message) { return reactToastify.toast.error(message, toastOptions); });
548
+ }
549
+ else if (requestMethod === PUT) {
550
+ return convertForRequestBody(query, fullTableList, function (message) { return reactToastify.toast.error(message, toastOptions); });
551
+ }
552
+ else if (requestMethod === DELETE) {
553
+ return {
554
+ data: convertForRequestBody(query, fullTableList, function (message) { return reactToastify.toast.error(message, toastOptions); })
555
+ };
556
+ }
557
+ else {
558
+ throw new Error('The request method (' + requestMethod + ') was not recognized.');
559
+ }
560
+ })());
561
+ if (cachingConfirmed) {
562
+ // push to cache so we do not repeat the request
563
+ apiRequestCache.push({
564
+ requestArgumentsSerialized: querySerialized,
565
+ request: axiosActiveRequest
566
+ });
567
+ }
568
+ // https://rapidapi.com/guides/axios-async-await
569
+ return axiosActiveRequest.then(function (response) {
570
+ var _a, _b, _c, _d, _e, _f, _g, _h;
571
+ if (typeof response.data === 'string') {
572
+ if (isTest) {
573
+ console.trace();
574
+ 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 + ')');
575
+ }
576
+ return Promise.reject(response);
577
+ }
578
+ 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!");
579
+ if (false !== apiResponse) {
580
+ responseCallback(response, request, apiResponse);
581
+ if (C6.GET === requestMethod) {
582
+ var responseData = response.data;
583
+ // @ts-ignore
584
+ returnGetNextPageFunction = 1 !== ((_b = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _b === void 0 ? void 0 : _b[C6.LIMIT]) &&
585
+ ((_c = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _c === void 0 ? void 0 : _c[C6.LIMIT]) === responseData.rest.length;
586
+ if (false === isTest || true === isVerbose) {
587
+ 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');
588
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
589
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', request);
590
+ console.log('%c Response Data:', 'color: #0c0', responseData.rest);
591
+ 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);
592
+ console.trace();
593
+ console.groupEnd();
594
+ }
595
+ if (false === returnGetNextPageFunction
596
+ && true === request.debug
597
+ && isLocal) {
598
+ 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);
599
+ }
600
+ }
601
+ }
602
+ if (cachingConfirmed) {
603
+ var cacheIndex = apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
604
+ apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction;
605
+ // only cache get method requests
606
+ apiRequestCache[cacheIndex].response = response;
607
+ }
608
+ if (request.debug && isLocal) {
609
+ reactToastify.toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
610
+ }
611
+ return response;
612
+ });
613
+ }
614
+ catch (error) {
615
+ if (isTest) {
616
+ throw new Error(JSON.stringify(error));
617
+ }
618
+ console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
619
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
620
+ console.warn(error);
621
+ console.trace();
622
+ console.groupEnd();
623
+ 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!");
624
+ return null;
625
+ }
626
+ }
627
+ return apiRequest();
628
+ };
629
+ }
630
+
631
+ exports.C6 = C6;
632
+ exports.DELETE = DELETE;
633
+ exports.GET = GET;
634
+ exports.POST = POST;
635
+ exports.PUT = PUT;
636
+ exports.TestRestfulResponse = TestRestfulResponse;
637
+ exports.checkAllRequestsComplete = checkAllRequestsComplete;
638
+ exports.clearCache = clearCache;
639
+ exports.convertForRequestBody = convertForRequestBody;
640
+ exports.extendedTypeHints = extendedTypeHints;
641
+ exports.isLocal = isLocal;
642
+ exports.isPromise = isPromise;
643
+ exports.isTest = isTest;
644
+ exports.isVerbose = isVerbose;
645
+ exports.removeInvalidKeys = removeInvalidKeys;
646
+ exports.restRequest = restApi;
647
+ exports.toastOptions = toastOptions;
648
+ exports.toastOptionsDevs = toastOptionsDevs;
649
+ //# sourceMappingURL=index.cjs.js.map