@carbonorm/carbonnode 2.0.34 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/builders/sqlBuilder.d.ts +3 -0
- package/dist/api/carbonSqlExecutor.d.ts +17 -0
- package/dist/api/convertForRequestBody.d.ts +1 -1
- package/dist/api/executors/Executor.d.ts +18 -0
- package/dist/api/executors/HttpExecutor.d.ts +15 -0
- package/dist/api/executors/SqlExecutor.d.ts +11 -0
- package/dist/api/interfaces/ormInterfaces.d.ts +22 -1
- package/dist/api/rest/Blog_Categories.d.ts +37 -0
- package/dist/api/rest/Blog_Categories.test.d.ts +11 -0
- package/dist/api/rest/Blog_Images.d.ts +37 -0
- package/dist/api/rest/Blog_Images.test.d.ts +15 -0
- package/dist/api/rest/Blog_Post_Categories.d.ts +37 -0
- package/dist/api/rest/Blog_Post_Categories.test.d.ts +13 -0
- package/dist/api/rest/Blog_Post_Tags.d.ts +37 -0
- package/dist/api/rest/Blog_Post_Tags.test.d.ts +13 -0
- package/dist/api/rest/Blog_Posts.d.ts +37 -0
- package/dist/api/rest/Blog_Posts.test.d.ts +21 -0
- package/dist/api/rest/Blog_Tags.d.ts +37 -0
- package/dist/api/rest/Blog_Tags.test.d.ts +11 -0
- package/dist/api/rest/C6.d.ts +1000 -0
- package/dist/api/rest/Cache.d.ts +37 -0
- package/dist/api/rest/Cache.test.d.ts +12 -0
- package/dist/api/rest/Cities.d.ts +37 -0
- package/dist/api/rest/Cities.test.d.ts +17 -0
- package/dist/api/rest/Counties.d.ts +37 -0
- package/dist/api/rest/Counties.test.d.ts +18 -0
- package/dist/api/rest/Countries.d.ts +37 -0
- package/dist/api/rest/Countries.test.d.ts +24 -0
- package/dist/api/rest/Geometries.d.ts +37 -0
- package/dist/api/rest/Geometries.test.d.ts +16 -0
- package/dist/api/rest/Images.d.ts +37 -0
- package/dist/api/rest/Images.test.d.ts +16 -0
- package/dist/api/rest/Land_Section_Info.d.ts +37 -0
- package/dist/api/rest/Land_Section_Info.test.d.ts +15 -0
- package/dist/api/rest/Neighborhoods.d.ts +37 -0
- package/dist/api/rest/Neighborhoods.test.d.ts +12 -0
- package/dist/api/rest/Parcel_Building_Details.d.ts +37 -0
- package/dist/api/rest/Parcel_Building_Details.test.d.ts +40 -0
- package/dist/api/rest/Parcel_Neighborhoods.d.ts +37 -0
- package/dist/api/rest/Parcel_Neighborhoods.test.d.ts +15 -0
- package/dist/api/rest/Parcel_Owners.d.ts +37 -0
- package/dist/api/rest/Parcel_Owners.test.d.ts +23 -0
- package/dist/api/rest/Parcel_Sales.d.ts +37 -0
- package/dist/api/rest/Parcel_Sales.test.d.ts +19 -0
- package/dist/api/rest/Parcel_Tax_History.d.ts +37 -0
- package/dist/api/rest/Parcel_Tax_History.test.d.ts +24 -0
- package/dist/api/rest/Parcels.d.ts +37 -0
- package/dist/api/rest/Parcels.test.d.ts +42 -0
- package/dist/api/rest/Payment_Charge_Logs.d.ts +37 -0
- package/dist/api/rest/Payment_Charge_Logs.test.d.ts +17 -0
- package/dist/api/rest/Payment_Subscriptions.d.ts +37 -0
- package/dist/api/rest/Payment_Subscriptions.test.d.ts +20 -0
- package/dist/api/rest/Property_Units.d.ts +37 -0
- package/dist/api/rest/Property_Units.test.d.ts +55 -0
- package/dist/api/rest/Sources.d.ts +37 -0
- package/dist/api/rest/Sources.test.d.ts +17 -0
- package/dist/api/rest/States.d.ts +37 -0
- package/dist/api/rest/States.test.d.ts +20 -0
- package/dist/api/rest/Tax_Districts.d.ts +37 -0
- package/dist/api/rest/Tax_Districts.test.d.ts +12 -0
- package/dist/api/rest/Users.d.ts +37 -0
- package/dist/api/rest/Users.test.d.ts +14 -0
- package/dist/api/rest/Valuation_Reports.d.ts +37 -0
- package/dist/api/rest/Valuation_Reports.test.d.ts +36 -0
- package/dist/api/rest/Zip_Codes.d.ts +37 -0
- package/dist/api/rest/Zip_Codes.test.d.ts +15 -0
- package/dist/api/restRequest.d.ts +5 -141
- package/dist/api/types/dynamicFetching.d.ts +10 -0
- package/dist/api/types/modifyTypes.d.ts +9 -0
- package/dist/api/types/mysqlTypes.d.ts +4 -0
- package/dist/api/types/ormInterfaces.d.ts +223 -0
- package/dist/api/utils/apiHelpers.d.ts +9 -0
- package/dist/api/utils/cacheManager.d.ts +10 -0
- package/dist/api/utils/logger.d.ts +7 -0
- package/dist/api/utils/sortAndSerializeQueryObject.d.ts +1 -0
- package/dist/api/utils/testHelpers.d.ts +1 -0
- package/dist/api/utils/toastNotifier.d.ts +2 -0
- package/dist/index.cjs.js +973 -537
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +16 -1
- package/dist/index.esm.js +958 -537
- package/dist/index.esm.js.map +1 -1
- package/dist/variables/isNode.d.ts +2 -0
- package/package.json +32 -6
- package/scripts/assets/handlebars/C6.ts.handlebars +5 -1
- package/scripts/generateRestBindings.cjs +89 -23
- package/scripts/generateRestBindings.ts +100 -27
- package/src/api/builders/sqlBuilder.ts +173 -0
- package/src/api/convertForRequestBody.ts +1 -2
- package/src/api/executors/Executor.ts +26 -0
- package/src/api/executors/HttpExecutor.ts +790 -0
- package/src/api/executors/SqlExecutor.ts +90 -0
- package/src/api/restRequest.ts +20 -1128
- package/src/api/types/dynamicFetching.ts +10 -0
- package/src/api/types/modifyTypes.ts +25 -0
- package/src/api/types/mysqlTypes.ts +33 -0
- package/src/api/types/ormInterfaces.ts +287 -0
- package/src/api/utils/apiHelpers.ts +83 -0
- package/src/api/utils/cacheManager.ts +67 -0
- package/src/api/utils/logger.ts +24 -0
- package/src/api/utils/sortAndSerializeQueryObject.ts +12 -0
- package/src/api/utils/testHelpers.ts +24 -0
- package/src/api/utils/toastNotifier.ts +11 -0
- package/src/index.ts +16 -1
- package/src/variables/isNode.ts +3 -0
- package/src/api/interfaces/ormInterfaces.ts +0 -79
package/src/api/restRequest.ts
CHANGED
|
@@ -1,378 +1,10 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
4
|
-
import {AxiosInstance, AxiosPromise, AxiosResponse} from "axios";
|
|
5
|
-
|
|
6
|
-
import {toast} from "react-toastify";
|
|
7
|
-
import isLocal from "variables/isLocal";
|
|
8
|
-
import isTest from "variables/isTest";
|
|
9
|
-
import isVerbose from "variables/isVerbose";
|
|
10
|
-
import {toastOptions, toastOptionsDevs} from "variables/toastOptions";
|
|
11
|
-
|
|
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: {
|
|
48
|
-
[key: string]: (iC6RestfulModel & { [key: string]: any })
|
|
49
|
-
}): iRestObject {
|
|
50
|
-
|
|
51
|
-
let intersection: iRestObject = {} as iRestObject
|
|
52
|
-
|
|
53
|
-
let restfulObjectKeys: string[] = [];
|
|
54
|
-
|
|
55
|
-
const tableList = Object.values(c6Tables)
|
|
56
|
-
|
|
57
|
-
tableList.forEach(table => Object.values(table.COLUMNS).forEach(column => {
|
|
58
|
-
|
|
59
|
-
if (false === restfulObjectKeys.includes(column)) {
|
|
60
|
-
|
|
61
|
-
restfulObjectKeys.push(column)
|
|
62
|
-
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
}))
|
|
66
|
-
|
|
67
|
-
Object.keys(request).forEach(key => {
|
|
68
|
-
|
|
69
|
-
if (restfulObjectKeys.includes(key)) {
|
|
70
|
-
|
|
71
|
-
intersection[key] = request[key]
|
|
72
|
-
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
isTest || console.log('intersection', intersection)
|
|
78
|
-
|
|
79
|
-
return intersection
|
|
80
|
-
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
// if you can get away with modify over modifyDeep, use modify. The editor will be happier.
|
|
84
|
-
export type Modify<T, R> = Omit<T, keyof R> & R;
|
|
85
|
-
|
|
86
|
-
// @link https://stackoverflow.com/questions/41285211/overriding-interface-property-type-defined-in-typescript-d-ts-file/55032655#55032655
|
|
87
|
-
export type ModifyDeep<A, B extends DeepPartialAny<A>> = {
|
|
88
|
-
[K in keyof A | keyof B]?: // For all keys in A and B:
|
|
89
|
-
K extends keyof A // ───┐
|
|
90
|
-
? K extends keyof B // ───┼─ key K exists in both A and B
|
|
91
|
-
? A[K] extends AnyObject // │ ┴──┐
|
|
92
|
-
? B[K] extends AnyObject // │ ───┼─ both A and B are objects
|
|
93
|
-
? ModifyDeep<A[K], B[K]> // │ │ └─── We need to go deeper (recursively)
|
|
94
|
-
: B[K] // │ ├─ B is a primitive 🠆 use B as the final type (new type)
|
|
95
|
-
: B[K] // │ └─ A is a primitive 🠆 use B as the final type (new type)
|
|
96
|
-
: A[K] // ├─ key only exists in A 🠆 use A as the final type (original type)
|
|
97
|
-
: B[K] // └─ key only exists in B 🠆 use B as the final type (new type)
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
type AnyObject = Record<string, any>
|
|
101
|
-
|
|
102
|
-
// This type is here only for some intellisense for the overrides object
|
|
103
|
-
type DeepPartialAny<T> = {
|
|
104
|
-
/** Makes each property optional and turns each leaf property into any, allowing for type overrides by narrowing any. */
|
|
105
|
-
[P in keyof T]?: T[P] extends AnyObject ? DeepPartialAny<T[P]> : any
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
export enum eFetchDependencies {
|
|
109
|
-
NONE = 0,
|
|
110
|
-
REFERENCED = 0b1,
|
|
111
|
-
CHILDREN = 0b1,
|
|
112
|
-
REFERENCES = 0b10,
|
|
113
|
-
PARENTS = 0b10,
|
|
114
|
-
ALL = 0b11,
|
|
115
|
-
C6ENTITY = 0b100,
|
|
116
|
-
RECURSIVE = 0b1000,
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
// todo - I don't like that these essentially become reserved words.
|
|
120
|
-
export type iAPI<RestTableInterfaces extends { [key: string]: any }> = RestTableInterfaces & {
|
|
121
|
-
dataInsertMultipleRows?: RestTableInterfaces[],
|
|
122
|
-
cacheResults?: boolean, // aka ignoreCache
|
|
123
|
-
// todo - this should really only be used for get requests - add this to the Get interface or throw error (im actually inclined to ts ignore the function and add to iGetC6 atm; back later)
|
|
124
|
-
fetchDependencies?: number | eFetchDependencies | Awaited<apiReturn<iGetC6RestResponse<any>>>[],
|
|
125
|
-
debug?: boolean,
|
|
126
|
-
success?: string | ((r: AxiosResponse) => (string | void)),
|
|
127
|
-
error?: string | ((r: AxiosResponse) => (string | void)),
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
interface iCacheAPI<ResponseDataType = any> {
|
|
131
|
-
requestArgumentsSerialized: string,
|
|
132
|
-
request: AxiosPromise<ResponseDataType>,
|
|
133
|
-
response?: AxiosResponse,
|
|
134
|
-
final?: boolean,
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
// do not remove entries from this array. It is used to track the progress of API requests.
|
|
139
|
-
// position in array is important. Do not sort. To not add to begging.
|
|
140
|
-
let apiRequestCache: iCacheAPI[] = [];
|
|
141
|
-
|
|
142
|
-
let userCustomClearCache: (() => void)[] = [];
|
|
143
|
-
|
|
144
|
-
export function checkAllRequestsComplete(): true | (string[]) {
|
|
145
|
-
|
|
146
|
-
const stillRunning = apiRequestCache.filter((cache) => undefined === cache.response)
|
|
147
|
-
|
|
148
|
-
if (stillRunning.length !== 0) {
|
|
149
|
-
|
|
150
|
-
if (document === null || document === undefined) {
|
|
151
|
-
|
|
152
|
-
throw new Error('document is undefined while waiting for API requests to complete (' + JSON.stringify(apiRequestCache) + ')')
|
|
153
|
-
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
// when requests return emtpy sets in full renders, it may not be possible to track their progress.
|
|
157
|
-
console.warn('stillRunning...', stillRunning)
|
|
158
|
-
|
|
159
|
-
return stillRunning.map((cache) => cache.requestArgumentsSerialized)
|
|
160
|
-
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
return true
|
|
164
|
-
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
interface iClearCache {
|
|
169
|
-
ignoreWarning: boolean
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
function checkCache<ResponseDataType = any, RestShortTableNames = string>(cacheResult: iCacheAPI<ResponseDataType>, requestMethod: string, tableName: RestShortTableNames | RestShortTableNames[], request: any): false | undefined | null | AxiosPromise<ResponseDataType> {
|
|
174
|
-
|
|
175
|
-
if (undefined === cacheResult?.response) {
|
|
176
|
-
|
|
177
|
-
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')
|
|
178
|
-
|
|
179
|
-
console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0')
|
|
180
|
-
|
|
181
|
-
console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', request)
|
|
182
|
-
|
|
183
|
-
console.groupEnd()
|
|
184
|
-
|
|
185
|
-
return cacheResult.request;
|
|
186
|
-
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
if (true === cacheResult?.final) {
|
|
190
|
-
|
|
191
|
-
if (false === isTest || true === isVerbose) {
|
|
192
|
-
|
|
193
|
-
console.groupCollapsed('%c API: Rest api cache (' + requestMethod + ' ' + tableName + ') has reached the final result. Returning undefined!', 'color: #cc0')
|
|
194
|
-
|
|
195
|
-
console.log('%c ' + requestMethod + ' ' + tableName, 'color: #cc0')
|
|
196
|
-
|
|
197
|
-
console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #cc0', request)
|
|
198
|
-
|
|
199
|
-
console.log('%c Response Data:', 'color: #cc0', cacheResult?.response?.data?.rest || cacheResult?.response?.data || cacheResult?.response)
|
|
200
|
-
|
|
201
|
-
console.groupEnd()
|
|
202
|
-
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
return undefined;
|
|
206
|
-
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
return false;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
function sortAndSerializeQueryObject(tables: String, query: Object) {
|
|
213
|
-
const orderedQuery = Object.keys(query).sort().reduce(
|
|
214
|
-
(obj, key) => {
|
|
215
|
-
obj[key] = query[key];
|
|
216
|
-
return obj;
|
|
217
|
-
},
|
|
218
|
-
{}
|
|
219
|
-
);
|
|
220
|
-
|
|
221
|
-
return tables + ' ' + JSON.stringify(orderedQuery);
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
export function clearCache(props?: iClearCache) {
|
|
226
|
-
|
|
227
|
-
if (false === props?.ignoreWarning) {
|
|
228
|
-
|
|
229
|
-
console.warn('The rest api clearCache should only be used with extreme care! Avoid using this in favor of using `cacheResults : boolean`.')
|
|
230
|
-
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
userCustomClearCache.map((f) => 'function' === typeof f && f());
|
|
234
|
-
|
|
235
|
-
userCustomClearCache = apiRequestCache = []
|
|
236
|
-
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
export function removePrefixIfExists(tableName: string, prefix: string): string {
|
|
241
|
-
if (tableName.startsWith(prefix.toLowerCase())) {
|
|
242
|
-
return tableName.slice(prefix.length);
|
|
243
|
-
}
|
|
244
|
-
return tableName;
|
|
245
|
-
}
|
|
1
|
+
import isNode from '../variables/isNode';
|
|
2
|
+
import {Modify} from "./types/modifyTypes";
|
|
3
|
+
import {apiReturn, iAPI, iRest} from "./types/ormInterfaces";
|
|
246
4
|
|
|
247
5
|
/**
|
|
248
|
-
*
|
|
249
|
-
|
|
250
|
-
* Our api returns a zero argument function iff the method is get and the previous request reached the predefined limit.
|
|
251
|
-
* This function can be aliased as GetNextPageOfResults(). If the end is reached undefined will be returned.
|
|
252
|
-
*
|
|
253
|
-
*
|
|
254
|
-
* For POST, PUT, and DELETE requests one can expect the primary key of the new or modified index, or a boolean success
|
|
255
|
-
* indication if no primary key exists.
|
|
256
|
-
**/
|
|
257
|
-
export const POST = 'POST';
|
|
258
|
-
|
|
259
|
-
export const PUT = 'PUT';
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
export const GET = 'GET';
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
export const DELETE = 'DELETE';
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
export type iRestMethods = 'GET' | 'POST' | 'PUT' | 'DELETE';
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
//wip
|
|
272
|
-
export type RequestGetPutDeleteBody = {
|
|
273
|
-
SELECT?: any,
|
|
274
|
-
UPDATE?: any,
|
|
275
|
-
DELETE?: any,
|
|
276
|
-
WHERE?: any,
|
|
277
|
-
JOIN?: {
|
|
278
|
-
LEFT?: any,
|
|
279
|
-
RIGHT?: any,
|
|
280
|
-
INNER?: any,
|
|
281
|
-
},
|
|
282
|
-
PAGINATION?: {
|
|
283
|
-
PAGE?: number,
|
|
284
|
-
LIMIT?: number,
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
export type RequestQueryBody<RestTableInterfaces extends { [key: string]: any }> =
|
|
289
|
-
iAPI<RestTableInterfaces>
|
|
290
|
-
| RequestGetPutDeleteBody;
|
|
291
|
-
|
|
292
|
-
export function isPromise(x) {
|
|
293
|
-
return Object(x).constructor === Promise
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
interface iC6RestResponse<RestData> {
|
|
297
|
-
rest: RestData,
|
|
298
|
-
session?: any,
|
|
299
|
-
sql?: any
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
interface iChangeC6Data {
|
|
304
|
-
rowCount: number,
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
export interface iDeleteC6RestResponse<RestData = any, RequestData = any> extends iChangeC6Data, iC6RestResponse<RestData> {
|
|
308
|
-
deleted: boolean | number | string | RequestData,
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
export interface iPostC6RestResponse<RestData = any> extends iC6RestResponse<RestData> {
|
|
312
|
-
created: boolean | number | string,
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
export interface iPutC6RestResponse<RestData = any, RequestData = any> extends iChangeC6Data, iC6RestResponse<RestData> {
|
|
316
|
-
updated: boolean | number | string | RequestData,
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
export interface iC6Object {
|
|
320
|
-
C6VERSION: string,
|
|
321
|
-
TABLES: {
|
|
322
|
-
[key: string]: iC6RestfulModel &
|
|
323
|
-
{ [key: string]: string | number }
|
|
324
|
-
},
|
|
325
|
-
PREFIX: string,
|
|
326
|
-
IMPORT: (tableName: string) => Promise<iDynamicApiImport>,
|
|
327
|
-
|
|
328
|
-
[key: string]: any
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
// todo - I'm not sure that Modify<ResponseDataType, ResponseDataOverrides>[]> is needed?
|
|
332
|
-
export type iGetC6RestResponse<ResponseDataType, ResponseDataOverrides = {}> = iC6RestResponse<Modify<ResponseDataType, ResponseDataOverrides> | Modify<ResponseDataType, ResponseDataOverrides>[]>
|
|
333
|
-
|
|
334
|
-
// returning undefined means no more results are available, thus we've queried everything possible
|
|
335
|
-
// null means the request is currently being executed
|
|
336
|
-
// https://www.typescriptlang.org/docs/handbook/2/conditional-types.html
|
|
337
|
-
export type apiReturn<Response> =
|
|
338
|
-
null
|
|
339
|
-
| undefined
|
|
340
|
-
| AxiosPromise<Response>
|
|
341
|
-
| (Response extends iPutC6RestResponse | iDeleteC6RestResponse | iPostC6RestResponse ? null : (() => apiReturn<Response>))
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
interface iRest<CustomAndRequiredFields extends { [key: string]: any }, RestTableInterfaces extends {
|
|
345
|
-
[key: string]: any
|
|
346
|
-
}, RequestTableOverrides = {
|
|
347
|
-
[key in keyof RestTableInterfaces]: any
|
|
348
|
-
}, ResponseDataType = any,
|
|
349
|
-
RestShortTableNames extends string = any> {
|
|
350
|
-
C6: iC6Object,
|
|
351
|
-
axios?: AxiosInstance,
|
|
352
|
-
restURL?: string,
|
|
353
|
-
withCredentials?: boolean,
|
|
354
|
-
tableName: RestShortTableNames | RestShortTableNames[],
|
|
355
|
-
requestMethod: iRestMethods,
|
|
356
|
-
clearCache?: () => void,
|
|
357
|
-
skipPrimaryCheck?: boolean,
|
|
358
|
-
queryCallback: RequestQueryBody<Modify<RestTableInterfaces, RequestTableOverrides>> | ((request: iAPI<Modify<RestTableInterfaces, RequestTableOverrides>> & CustomAndRequiredFields) => (null | undefined | RequestQueryBody<Modify<RestTableInterfaces, RequestTableOverrides>>)),
|
|
359
|
-
responseCallback?: (response: AxiosResponse<ResponseDataType>,
|
|
360
|
-
request: iAPI<Modify<RestTableInterfaces, RequestTableOverrides>> & CustomAndRequiredFields,
|
|
361
|
-
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
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
export function extendedTypeHints<RestTableInterfaces extends {
|
|
365
|
-
[key: string]: any
|
|
366
|
-
}, RestShortTableNames extends string>() {
|
|
367
|
-
return <CustomAndRequiredFields extends {
|
|
368
|
-
[key: string]: any
|
|
369
|
-
} = any, RequestTableTypes extends RestTableInterfaces = any, RequestTableOverrides extends {
|
|
370
|
-
[key: string]: any
|
|
371
|
-
} = any, ResponseDataType extends {
|
|
372
|
-
[key: string]: any
|
|
373
|
-
} = any>(argv) => restRequest<CustomAndRequiredFields, RequestTableTypes, RequestTableOverrides, ResponseDataType, RestShortTableNames>(argv)
|
|
374
|
-
}
|
|
375
|
-
|
|
6
|
+
* Facade: routes API calls to SQL or HTTP executors based on runtime context.
|
|
7
|
+
*/
|
|
376
8
|
export default function restRequest<
|
|
377
9
|
CustomAndRequiredFields extends {
|
|
378
10
|
[key: string]: any;
|
|
@@ -385,763 +17,23 @@ export default function restRequest<
|
|
|
385
17
|
} = any,
|
|
386
18
|
ResponseDataType = any,
|
|
387
19
|
RestShortTableNames extends string = any
|
|
388
|
-
>(
|
|
389
|
-
|
|
390
|
-
axios = axiosInstance,
|
|
391
|
-
restURL = '/rest/',
|
|
392
|
-
withCredentials = true,
|
|
393
|
-
tableName,
|
|
394
|
-
requestMethod = GET,
|
|
395
|
-
queryCallback = {},
|
|
396
|
-
responseCallback,
|
|
397
|
-
skipPrimaryCheck = false,
|
|
398
|
-
clearCache = undefined
|
|
399
|
-
}: iRest<CustomAndRequiredFields, RestTableInterfaces, RequestTableOverrides, ResponseDataType, RestShortTableNames>
|
|
20
|
+
>(
|
|
21
|
+
config: iRest<CustomAndRequiredFields, RestTableInterfaces, RequestTableOverrides, ResponseDataType, RestShortTableNames>
|
|
400
22
|
) {
|
|
23
|
+
return async (
|
|
24
|
+
request: iAPI<Modify<RestTableInterfaces, RequestTableOverrides>> & CustomAndRequiredFields = {} as iAPI<Modify<RestTableInterfaces, RequestTableOverrides>> & CustomAndRequiredFields
|
|
25
|
+
): Promise<apiReturn<ResponseDataType>> => {
|
|
401
26
|
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
const tables = fullTableList.join(',')
|
|
409
|
-
|
|
410
|
-
switch (requestMethod) {
|
|
411
|
-
case GET:
|
|
412
|
-
case POST:
|
|
413
|
-
case PUT:
|
|
414
|
-
case DELETE:
|
|
415
|
-
break;
|
|
416
|
-
default:
|
|
417
|
-
throw Error('Bad request method passed to getApi')
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
if (null !== clearCache || undefined !== clearCache) {
|
|
421
|
-
|
|
422
|
-
userCustomClearCache[tables + requestMethod] = clearCache;
|
|
423
|
-
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
return (request: iAPI<Modify<RestTableInterfaces, RequestTableOverrides>> & CustomAndRequiredFields = {} as iAPI<Modify<RestTableInterfaces, RequestTableOverrides>> & CustomAndRequiredFields) => {
|
|
427
|
-
|
|
428
|
-
console.groupCollapsed('%c API: (' + requestMethod + ') Request for (' + operatingTable + ')', 'color: #0c0')
|
|
429
|
-
|
|
430
|
-
console.log('request', request)
|
|
431
|
-
|
|
432
|
-
console.groupEnd()
|
|
433
|
-
|
|
434
|
-
// an undefined query would indicate queryCallback returned undefined,
|
|
435
|
-
// thus the request shouldn't fire as is in custom cache
|
|
436
|
-
let query: RequestQueryBody<Modify<RestTableInterfaces, RequestTableOverrides>> | undefined | null;
|
|
437
|
-
|
|
438
|
-
if ('function' === typeof queryCallback) {
|
|
439
|
-
|
|
440
|
-
query = queryCallback(request); // obj or obj[]
|
|
441
|
-
|
|
442
|
-
} else {
|
|
443
|
-
|
|
444
|
-
query = queryCallback;
|
|
445
|
-
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
if (undefined === query || null === query) {
|
|
449
|
-
|
|
450
|
-
if (request.debug && isLocal) {
|
|
451
|
-
|
|
452
|
-
toast.warning("DEV: queryCallback returned undefined, signaling in Custom Cache. (returning null)", toastOptionsDevs)
|
|
453
|
-
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') undefined, returning null (will not fire ajax)!', 'color: #c00')
|
|
457
|
-
|
|
458
|
-
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')
|
|
459
|
-
|
|
460
|
-
console.trace();
|
|
461
|
-
|
|
462
|
-
console.groupEnd()
|
|
463
|
-
|
|
464
|
-
return null;
|
|
465
|
-
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
if (C6.GET === requestMethod) {
|
|
469
|
-
|
|
470
|
-
if (undefined === query[C6.PAGINATION]) {
|
|
471
|
-
|
|
472
|
-
query[C6.PAGINATION] = {}
|
|
473
|
-
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
|
|
477
|
-
|
|
478
|
-
query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
|
|
479
|
-
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
// this could return itself with a new page number, or undefined if the end is reached
|
|
483
|
-
function apiRequest(): apiReturn<ResponseDataType> {
|
|
484
|
-
|
|
485
|
-
request.cacheResults ??= (C6.GET === requestMethod)
|
|
486
|
-
|
|
487
|
-
if (C6.GET === requestMethod
|
|
488
|
-
&& undefined !== query?.[C6.PAGINATION]?.[C6.PAGE]
|
|
489
|
-
&& 1 !== query[C6.PAGINATION][C6.PAGE]) {
|
|
490
|
-
|
|
491
|
-
console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!')
|
|
492
|
-
|
|
493
|
-
console.log('Request Data (note you may see the success and/or error prompt):', request)
|
|
494
|
-
|
|
495
|
-
console.trace();
|
|
496
|
-
|
|
497
|
-
console.groupEnd()
|
|
498
|
-
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
// 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.
|
|
502
|
-
// 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
|
|
503
|
-
|
|
504
|
-
// literally impossible for query to be undefined or null here but the editor is too busy licking windows to understand that
|
|
505
|
-
let querySerialized: string = sortAndSerializeQueryObject(tables, query ?? {});
|
|
506
|
-
|
|
507
|
-
let cacheResult: iCacheAPI | undefined = apiRequestCache.find(cache => cache.requestArgumentsSerialized === querySerialized);
|
|
508
|
-
|
|
509
|
-
let cachingConfirmed = false;
|
|
510
|
-
|
|
511
|
-
// determine if we need to paginate.
|
|
512
|
-
if (requestMethod === C6.GET) {
|
|
513
|
-
|
|
514
|
-
if (undefined === query?.[C6.PAGINATION]) {
|
|
515
|
-
|
|
516
|
-
if (undefined === query || null === query) {
|
|
517
|
-
|
|
518
|
-
query = {}
|
|
519
|
-
|
|
520
|
-
}
|
|
521
|
-
|
|
522
|
-
query[C6.PAGINATION] = {}
|
|
523
|
-
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
|
|
527
|
-
|
|
528
|
-
query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
|
|
529
|
-
|
|
530
|
-
// this will evaluate true most the time
|
|
531
|
-
if (true === request.cacheResults) {
|
|
532
|
-
|
|
533
|
-
// just find the next, non-fetched, page and return a function to request it
|
|
534
|
-
if (undefined !== cacheResult) {
|
|
535
|
-
|
|
536
|
-
do {
|
|
537
|
-
|
|
538
|
-
const cacheCheck = checkCache<ResponseDataType>(cacheResult, requestMethod, tableName, request);
|
|
539
|
-
|
|
540
|
-
if (false !== cacheCheck) {
|
|
541
|
-
|
|
542
|
-
return cacheCheck;
|
|
543
|
-
|
|
544
|
-
}
|
|
545
|
-
|
|
546
|
-
// this line incrementing page is why we return recursively
|
|
547
|
-
++query[C6.PAGINATION][C6.PAGE];
|
|
548
|
-
|
|
549
|
-
// this json stringify is to capture the new page number
|
|
550
|
-
querySerialized = sortAndSerializeQueryObject(tables, query ?? {});
|
|
551
|
-
|
|
552
|
-
cacheResult = apiRequestCache.find(cache => cache.requestArgumentsSerialized === querySerialized)
|
|
553
|
-
|
|
554
|
-
} while (undefined !== cacheResult)
|
|
555
|
-
|
|
556
|
-
if (request.debug && isLocal) {
|
|
557
|
-
|
|
558
|
-
toast.warning("DEVS: Request in cache. (" + apiRequestCache.findIndex(cache => cache.requestArgumentsSerialized === querySerialized) + "). Returning function to request page (" + query[C6.PAGINATION][C6.PAGE] + ")", toastOptionsDevs);
|
|
559
|
-
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
// @ts-ignore - this is an incorrect warning on TS, it's well typed
|
|
563
|
-
return apiRequest;
|
|
564
|
-
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
cachingConfirmed = true;
|
|
568
|
-
|
|
569
|
-
} else {
|
|
570
|
-
|
|
571
|
-
if (request.debug && isLocal) {
|
|
572
|
-
|
|
573
|
-
toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
|
|
574
|
-
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
if (request.debug && isLocal) {
|
|
580
|
-
|
|
581
|
-
toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
|
|
582
|
-
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
} else if (request.cacheResults) { // if we are not getting, we are updating, deleting, or inserting
|
|
586
|
-
|
|
587
|
-
if (cacheResult) {
|
|
588
|
-
const cacheCheck = checkCache<ResponseDataType>(cacheResult, requestMethod, tableName, request);
|
|
589
|
-
|
|
590
|
-
if (false !== cacheCheck) {
|
|
591
|
-
|
|
592
|
-
return cacheCheck;
|
|
593
|
-
|
|
594
|
-
}
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
cachingConfirmed = true;
|
|
598
|
-
// push to cache so we do not repeat the request
|
|
599
|
-
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
let addBackPK: (() => void) | undefined;
|
|
603
|
-
|
|
604
|
-
let apiResponse: string | boolean | number | undefined;
|
|
605
|
-
|
|
606
|
-
let returnGetNextPageFunction = false;
|
|
607
|
-
|
|
608
|
-
let restRequestUri: string = restURL + operatingTable + '/';
|
|
609
|
-
|
|
610
|
-
const needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
|
|
611
|
-
&& false === skipPrimaryCheck;
|
|
612
|
-
|
|
613
|
-
const TABLES = C6.TABLES;
|
|
614
|
-
|
|
615
|
-
// todo - aggregate primary key check with condition check
|
|
616
|
-
// check if PK exists in query, clone so pop does not affect the real data
|
|
617
|
-
const primaryKey = structuredClone(TABLES[operatingTable]?.PRIMARY)?.pop()?.split('.')?.pop();
|
|
618
|
-
|
|
619
|
-
if (needsConditionOrPrimaryCheck) {
|
|
620
|
-
|
|
621
|
-
if (undefined === primaryKey) {
|
|
622
|
-
|
|
623
|
-
if (null === query
|
|
624
|
-
|| undefined === query
|
|
625
|
-
|| undefined === query?.[C6.WHERE]
|
|
626
|
-
|| (true === Array.isArray(query[C6.WHERE])
|
|
627
|
-
|| query[C6.WHERE].length === 0)
|
|
628
|
-
|| (Object.keys(query?.[C6.WHERE]).length === 0)
|
|
629
|
-
) {
|
|
630
|
-
|
|
631
|
-
console.error(query)
|
|
632
|
-
|
|
633
|
-
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 + ').')
|
|
634
|
-
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
} else {
|
|
638
|
-
|
|
639
|
-
if (undefined === query
|
|
640
|
-
|| null === query
|
|
641
|
-
|| false === primaryKey in query) {
|
|
642
|
-
|
|
643
|
-
if (true === request.debug && isLocal) {
|
|
644
|
-
|
|
645
|
-
toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!')
|
|
646
|
-
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
|
|
650
|
-
|
|
651
|
-
}
|
|
652
|
-
|
|
653
|
-
if (undefined === query?.[primaryKey]
|
|
654
|
-
|| null === query?.[primaryKey]) {
|
|
655
|
-
|
|
656
|
-
toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!')
|
|
657
|
-
|
|
658
|
-
throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
|
|
659
|
-
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
}
|
|
665
|
-
|
|
666
|
-
// A part of me exists that wants to remove this, but it's a good feature
|
|
667
|
-
// this allows developers the ability to cache requests based on primary key
|
|
668
|
-
// for tables like `photos` this can be a huge performance boost
|
|
669
|
-
if (undefined !== query
|
|
670
|
-
&& null !== query
|
|
671
|
-
&& undefined !== primaryKey
|
|
672
|
-
&& primaryKey in query) {
|
|
673
|
-
|
|
674
|
-
restRequestUri += query[primaryKey] + '/'
|
|
675
|
-
|
|
676
|
-
const removedPkValue = query[primaryKey];
|
|
677
|
-
|
|
678
|
-
addBackPK = () => {
|
|
679
|
-
query ??= {}
|
|
680
|
-
query[primaryKey] = removedPkValue
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
delete query[primaryKey]
|
|
684
|
-
|
|
685
|
-
console.log('query', query, 'primaryKey', primaryKey, 'removedPkValue', removedPkValue)
|
|
686
|
-
|
|
687
|
-
} else {
|
|
688
|
-
|
|
689
|
-
console.log('query', query)
|
|
690
|
-
|
|
691
|
-
}
|
|
692
|
-
|
|
693
|
-
try {
|
|
694
|
-
|
|
695
|
-
console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0')
|
|
696
|
-
|
|
697
|
-
console.log(request)
|
|
698
|
-
|
|
699
|
-
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')
|
|
700
|
-
|
|
701
|
-
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')
|
|
702
|
-
|
|
703
|
-
console.trace()
|
|
704
|
-
|
|
705
|
-
console.groupEnd()
|
|
706
|
-
|
|
707
|
-
const axiosActiveRequest: AxiosPromise<ResponseDataType> = axios[requestMethod.toLowerCase()]<ResponseDataType>(
|
|
708
|
-
restRequestUri,
|
|
709
|
-
...((() => {
|
|
710
|
-
|
|
711
|
-
// @link - https://axios-http.com/docs/instance
|
|
712
|
-
// How configuration vs data is passed is variable, use documentation above for reference
|
|
713
|
-
if (requestMethod === GET) {
|
|
714
|
-
|
|
715
|
-
return [{
|
|
716
|
-
withCredentials: withCredentials,
|
|
717
|
-
params: query
|
|
718
|
-
}]
|
|
719
|
-
|
|
720
|
-
} else if (requestMethod === POST) {
|
|
721
|
-
|
|
722
|
-
if (undefined !== request?.dataInsertMultipleRows) {
|
|
723
|
-
|
|
724
|
-
return [
|
|
725
|
-
request.dataInsertMultipleRows.map(data =>
|
|
726
|
-
convertForRequestBody<typeof data>(data, fullTableList, C6, (message) => toast.error(message, toastOptions))),
|
|
727
|
-
{
|
|
728
|
-
withCredentials: withCredentials,
|
|
729
|
-
}
|
|
730
|
-
]
|
|
731
|
-
|
|
732
|
-
}
|
|
733
|
-
|
|
734
|
-
return [
|
|
735
|
-
convertForRequestBody<RestTableInterfaces>(query as RestTableInterfaces, fullTableList, C6, (message) => toast.error(message, toastOptions)),
|
|
736
|
-
{
|
|
737
|
-
withCredentials: withCredentials,
|
|
738
|
-
}
|
|
739
|
-
]
|
|
740
|
-
|
|
741
|
-
} else if (requestMethod === PUT) {
|
|
742
|
-
|
|
743
|
-
return [
|
|
744
|
-
convertForRequestBody<RestTableInterfaces>(query as RestTableInterfaces, fullTableList, C6, (message) => toast.error(message, toastOptions)),
|
|
745
|
-
{
|
|
746
|
-
withCredentials: withCredentials,
|
|
747
|
-
}
|
|
748
|
-
]
|
|
749
|
-
} else if (requestMethod === DELETE) {
|
|
750
|
-
|
|
751
|
-
return [{
|
|
752
|
-
withCredentials: withCredentials,
|
|
753
|
-
data: convertForRequestBody<RestTableInterfaces>(query as RestTableInterfaces, fullTableList, C6, (message) => toast.error(message, toastOptions))
|
|
754
|
-
}]
|
|
755
|
-
|
|
756
|
-
} else {
|
|
757
|
-
|
|
758
|
-
throw new Error('The request method (' + requestMethod + ') was not recognized.')
|
|
759
|
-
|
|
760
|
-
}
|
|
761
|
-
|
|
762
|
-
})())
|
|
763
|
-
);
|
|
764
|
-
|
|
765
|
-
if (cachingConfirmed) {
|
|
766
|
-
|
|
767
|
-
// push to cache so we do not repeat the request
|
|
768
|
-
apiRequestCache.push({
|
|
769
|
-
requestArgumentsSerialized: querySerialized,
|
|
770
|
-
request: axiosActiveRequest
|
|
771
|
-
});
|
|
772
|
-
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
// todo - wip verify this works
|
|
776
|
-
// we had removed the value from the request to add to the URI.
|
|
777
|
-
addBackPK?.(); // adding back so post-processing methods work
|
|
778
|
-
|
|
779
|
-
// returning the promise with this then is important for tests. todo - we could make that optional.
|
|
780
|
-
// https://rapidapi.com/guides/axios-async-await
|
|
781
|
-
return axiosActiveRequest.then(async (response): Promise<AxiosResponse<ResponseDataType, any>> => {
|
|
782
|
-
|
|
783
|
-
if (typeof response.data === 'string') {
|
|
784
|
-
|
|
785
|
-
if (isTest) {
|
|
786
|
-
|
|
787
|
-
console.trace()
|
|
788
|
-
|
|
789
|
-
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 + ')')
|
|
790
|
-
|
|
791
|
-
}
|
|
792
|
-
|
|
793
|
-
return Promise.reject(response);
|
|
794
|
-
|
|
795
|
-
}
|
|
796
|
-
|
|
797
|
-
if (cachingConfirmed) {
|
|
798
|
-
|
|
799
|
-
const cacheIndex = apiRequestCache.findIndex(cache => cache.requestArgumentsSerialized === querySerialized);
|
|
800
|
-
|
|
801
|
-
apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction
|
|
802
|
-
|
|
803
|
-
// only cache get method requests
|
|
804
|
-
apiRequestCache[cacheIndex].response = response
|
|
805
|
-
|
|
806
|
-
}
|
|
807
|
-
|
|
808
|
-
apiResponse = TestRestfulResponse(response, request?.success, request?.error ?? "An unexpected API error occurred!")
|
|
809
|
-
|
|
810
|
-
if (false === apiResponse) {
|
|
811
|
-
|
|
812
|
-
if (request.debug && isLocal) {
|
|
813
|
-
|
|
814
|
-
toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
|
|
815
|
-
|
|
816
|
-
}
|
|
817
|
-
|
|
818
|
-
return response;
|
|
819
|
-
|
|
820
|
-
}
|
|
821
|
-
|
|
822
|
-
// stateful operations are done in the response callback - its leverages rest generated functions
|
|
823
|
-
if (responseCallback) {
|
|
824
|
-
|
|
825
|
-
responseCallback(response, request, apiResponse)
|
|
826
|
-
|
|
827
|
-
}
|
|
828
|
-
|
|
829
|
-
if (C6.GET === requestMethod) {
|
|
830
|
-
|
|
831
|
-
const responseData = response.data as iGetC6RestResponse<any>;
|
|
832
|
-
|
|
833
|
-
returnGetNextPageFunction = 1 !== query?.[C6.PAGINATION]?.[C6.LIMIT] &&
|
|
834
|
-
query?.[C6.PAGINATION]?.[C6.LIMIT] === responseData.rest.length
|
|
835
|
-
|
|
836
|
-
if (false === isTest || true === isVerbose) {
|
|
837
|
-
|
|
838
|
-
console.groupCollapsed('%c API: Response (' + requestMethod + ' ' + tableName + ') returned length (' + responseData.rest?.length + ') of possible (' + query?.[C6.PAGINATION]?.[C6.LIMIT] + ') limit!', 'color: #0c0')
|
|
839
|
-
|
|
840
|
-
console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0')
|
|
841
|
-
|
|
842
|
-
console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', request)
|
|
843
|
-
|
|
844
|
-
console.log('%c Response Data:', 'color: #0c0', responseData.rest)
|
|
845
|
-
|
|
846
|
-
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)
|
|
847
|
-
|
|
848
|
-
console.trace();
|
|
849
|
-
|
|
850
|
-
console.groupEnd()
|
|
851
|
-
|
|
852
|
-
}
|
|
853
|
-
|
|
854
|
-
if (false === returnGetNextPageFunction
|
|
855
|
-
&& true === request.debug
|
|
856
|
-
&& isLocal) {
|
|
857
|
-
|
|
858
|
-
toast.success("DEVS: Response returned length (" + responseData.rest?.length + ") less than limit (" + query?.[C6.PAGINATION]?.[C6.LIMIT] + ").", toastOptionsDevs);
|
|
859
|
-
|
|
860
|
-
}
|
|
861
|
-
|
|
862
|
-
request.fetchDependencies ??= eFetchDependencies.NONE;
|
|
863
|
-
|
|
864
|
-
if (request.fetchDependencies
|
|
865
|
-
&& 'number' === typeof request.fetchDependencies
|
|
866
|
-
&& responseData.rest.length > 0) {
|
|
867
|
-
|
|
868
|
-
const fetchDependencies = request.fetchDependencies as number;
|
|
869
|
-
|
|
870
|
-
console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
|
|
871
|
-
+ (fetchDependencies & eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
|
|
872
|
-
+ (fetchDependencies & eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
|
|
873
|
-
+ (fetchDependencies & eFetchDependencies.C6ENTITY ? ' | (C6ENTITY)' : '')
|
|
874
|
-
+ (fetchDependencies & eFetchDependencies.RECURSIVE ? ' | (RECURSIVE)' : ''), 'color: #33ccff')
|
|
875
|
-
|
|
876
|
-
console.groupCollapsed('Collapsed JS Trace');
|
|
877
|
-
console.trace(); // hidden in collapsed group
|
|
878
|
-
console.groupEnd();
|
|
879
|
-
|
|
880
|
-
// noinspection JSBitwiseOperatorUsage
|
|
881
|
-
let dependencies: {
|
|
882
|
-
[key: string]: iConstraint[]
|
|
883
|
-
} = {};
|
|
884
|
-
|
|
885
|
-
if (fetchDependencies & eFetchDependencies.C6ENTITY) {
|
|
886
|
-
|
|
887
|
-
dependencies = operatingTable.endsWith("carbon_carbons")
|
|
888
|
-
? {
|
|
889
|
-
// the context of the entity system is a bit different
|
|
890
|
-
...fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
|
|
891
|
-
? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
|
|
892
|
-
: {},
|
|
893
|
-
...fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
|
|
894
|
-
? C6.TABLES[operatingTable].TABLE_REFERENCES
|
|
895
|
-
: {}
|
|
896
|
-
} : {
|
|
897
|
-
// the context of the entity system is a bit different
|
|
898
|
-
...fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
|
|
899
|
-
? {
|
|
900
|
-
...Object.keys(C6.TABLES[operatingTable].TABLE_REFERENCES).reduce((accumulator, columnName) => {
|
|
901
|
-
|
|
902
|
-
if (!C6.TABLES[operatingTable].PRIMARY_SHORT.includes(columnName)) {
|
|
903
|
-
accumulator[columnName] = C6.TABLES[operatingTable].TABLE_REFERENCES[columnName]
|
|
904
|
-
}
|
|
905
|
-
|
|
906
|
-
return accumulator
|
|
907
|
-
}, {}),
|
|
908
|
-
...C6.TABLES[operatingTable].TABLE_REFERENCED_BY // it is unlikely that a C6 table will have any TABLE_REFERENCED_BY
|
|
909
|
-
}
|
|
910
|
-
: {},
|
|
911
|
-
...fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
|
|
912
|
-
? C6.TABLES[operatingTable].PRIMARY_SHORT.reduce((accumulator, primaryKey) => {
|
|
913
|
-
if (primaryKey in C6.TABLES[operatingTable].TABLE_REFERENCES) {
|
|
914
|
-
accumulator[primaryKey] = C6.TABLES[operatingTable].TABLE_REFERENCES[primaryKey]
|
|
915
|
-
}
|
|
916
|
-
return accumulator
|
|
917
|
-
}, {})
|
|
918
|
-
: {}
|
|
919
|
-
}
|
|
920
|
-
|
|
921
|
-
} else {
|
|
922
|
-
|
|
923
|
-
// this is the natural mysql context
|
|
924
|
-
dependencies = {
|
|
925
|
-
...fetchDependencies & eFetchDependencies.REFERENCED // REFERENCED === CHILDREN
|
|
926
|
-
? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
|
|
927
|
-
: {},
|
|
928
|
-
...fetchDependencies & eFetchDependencies.REFERENCES // REFERENCES === PARENTS
|
|
929
|
-
? C6.TABLES[operatingTable].TABLE_REFERENCES
|
|
930
|
-
: {}
|
|
931
|
-
};
|
|
932
|
-
|
|
933
|
-
}
|
|
934
|
-
|
|
935
|
-
let fetchReferences: {
|
|
936
|
-
[externalTable: string]: {
|
|
937
|
-
[column: string]: string[]
|
|
938
|
-
}
|
|
939
|
-
} = {}
|
|
940
|
-
|
|
941
|
-
let apiRequestPromises: Array<apiReturn<iGetC6RestResponse<any>>> = []
|
|
942
|
-
|
|
943
|
-
console.log('%c Dependencies', 'color: #005555', dependencies)
|
|
944
|
-
|
|
945
|
-
Object.keys(dependencies)
|
|
946
|
-
.forEach(column => dependencies[column]
|
|
947
|
-
.forEach((constraint) => {
|
|
948
|
-
|
|
949
|
-
const columnValues = responseData.rest[column] ?? responseData.rest.map((row) => {
|
|
950
|
-
|
|
951
|
-
if (operatingTable.endsWith("carbons")
|
|
952
|
-
&& 'entity_tag' in row
|
|
953
|
-
&& !constraint.TABLE.endsWith(row['entity_tag'].split('\\').pop().toLowerCase())) {
|
|
954
|
-
|
|
955
|
-
return false; // map
|
|
956
|
-
|
|
957
|
-
}
|
|
958
|
-
|
|
959
|
-
if (!(column in row)) {
|
|
960
|
-
return false
|
|
961
|
-
}
|
|
962
|
-
|
|
963
|
-
// todo - row[column] is a FK value, we should optionally remove values that are already in state
|
|
964
|
-
// this could be any column in the table constraint.TABLE, not just the primary key
|
|
965
|
-
|
|
966
|
-
return row[column]
|
|
967
|
-
|
|
968
|
-
}).filter(n => n) ?? [];
|
|
969
|
-
|
|
970
|
-
if (columnValues.length === 0) {
|
|
971
|
-
|
|
972
|
-
return; // forEach
|
|
973
|
-
|
|
974
|
-
}
|
|
975
|
-
|
|
976
|
-
fetchReferences[constraint.TABLE] ??= {};
|
|
977
|
-
|
|
978
|
-
fetchReferences[constraint.TABLE][constraint.COLUMN] ??= []
|
|
979
|
-
|
|
980
|
-
fetchReferences[constraint.TABLE][constraint.COLUMN].push(columnValues)
|
|
981
|
-
|
|
982
|
-
}));
|
|
983
|
-
|
|
984
|
-
console.log('fetchReferences', fetchReferences)
|
|
985
|
-
|
|
986
|
-
for (const tableToFetch in fetchReferences) {
|
|
987
|
-
|
|
988
|
-
if (fetchDependencies & eFetchDependencies.C6ENTITY
|
|
989
|
-
&& 'string' === typeof tableName
|
|
990
|
-
&& tableName.endsWith("carbon_carbons")) {
|
|
991
|
-
|
|
992
|
-
// todo - rethink the table ref entity system - when tables are renamed? no hooks exist in mysql
|
|
993
|
-
// since were already filtering on column, we can assume the first row constraint is the same as the rest
|
|
994
|
-
|
|
995
|
-
const referencesTables: string[] = responseData.rest.reduce((accumulator: string[], row: {
|
|
996
|
-
[x: string]: string;
|
|
997
|
-
}) => {
|
|
998
|
-
if ('entity_tag' in row && !accumulator.includes(row['entity_tag'])) {
|
|
999
|
-
accumulator.push(row['entity_tag']);
|
|
1000
|
-
}
|
|
1001
|
-
return accumulator;
|
|
1002
|
-
}, []).map((entityTag) => entityTag.split('\\').pop().toLowerCase());
|
|
1003
|
-
|
|
1004
|
-
const shouldContinue = referencesTables.find((referencesTable) => tableToFetch.endsWith(referencesTable))
|
|
1005
|
-
|
|
1006
|
-
if (!shouldContinue) {
|
|
1007
|
-
|
|
1008
|
-
console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables)
|
|
1009
|
-
|
|
1010
|
-
continue;
|
|
1011
|
-
|
|
1012
|
-
}
|
|
1013
|
-
|
|
1014
|
-
console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') will be fetched.', 'color: #0c0')
|
|
1015
|
-
|
|
1016
|
-
}
|
|
1017
|
-
|
|
1018
|
-
const fetchTable = await C6.IMPORT(tableToFetch)
|
|
1019
|
-
|
|
1020
|
-
const RestApi = fetchTable.default
|
|
1021
|
-
|
|
1022
|
-
console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff')
|
|
1023
|
-
|
|
1024
|
-
let nextFetchDependencies = eFetchDependencies.NONE
|
|
1025
|
-
|
|
1026
|
-
if (fetchDependencies & eFetchDependencies.RECURSIVE) {
|
|
1027
|
-
|
|
1028
|
-
if (fetchDependencies & eFetchDependencies.ALL) {
|
|
1029
|
-
|
|
1030
|
-
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.')
|
|
1031
|
-
|
|
1032
|
-
}
|
|
1033
|
-
|
|
1034
|
-
nextFetchDependencies = fetchDependencies
|
|
1035
|
-
|
|
1036
|
-
} else if (fetchDependencies & eFetchDependencies.C6ENTITY) {
|
|
1037
|
-
|
|
1038
|
-
if (tableToFetch === "carbon_carbons") {
|
|
1039
|
-
|
|
1040
|
-
nextFetchDependencies = fetchDependencies
|
|
1041
|
-
|
|
1042
|
-
} else {
|
|
1043
|
-
|
|
1044
|
-
nextFetchDependencies = fetchDependencies ^ eFetchDependencies.C6ENTITY
|
|
1045
|
-
|
|
1046
|
-
}
|
|
1047
|
-
|
|
1048
|
-
}
|
|
1049
|
-
|
|
1050
|
-
console.log('fetchReferences', fetchReferences[tableToFetch], "Current fetchDependencies for (" + operatingTable + "):", fetchDependencies, "New fetchDependencies for (" + tableToFetch + "): ", nextFetchDependencies)
|
|
1051
|
-
|
|
1052
|
-
// 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
|
|
1053
|
-
// it not certain that they are using carbons' entities either
|
|
1054
|
-
|
|
1055
|
-
// this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
|
|
1056
|
-
// todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
|
|
1057
|
-
apiRequestPromises.push(RestApi.Get({
|
|
1058
|
-
[C6.WHERE]: {
|
|
1059
|
-
0: Object.keys(fetchReferences[tableToFetch]).reduce((sum, column) => {
|
|
1060
|
-
|
|
1061
|
-
fetchReferences[tableToFetch][column] = fetchReferences[tableToFetch][column].flat(Infinity)
|
|
1062
|
-
|
|
1063
|
-
if (0 === fetchReferences[tableToFetch][column].length) {
|
|
1064
|
-
|
|
1065
|
-
console.warn('The column (' + column + ') was not found in the response data. We will not fetch.', responseData)
|
|
1066
|
-
|
|
1067
|
-
return false;
|
|
1068
|
-
|
|
1069
|
-
}
|
|
1070
|
-
|
|
1071
|
-
sum[column] = fetchReferences[tableToFetch][column].length === 1
|
|
1072
|
-
? fetchReferences[tableToFetch][column][0]
|
|
1073
|
-
: [
|
|
1074
|
-
C6.IN, fetchReferences[tableToFetch][column]
|
|
1075
|
-
]
|
|
1076
|
-
|
|
1077
|
-
return sum
|
|
1078
|
-
|
|
1079
|
-
}, {})
|
|
1080
|
-
},
|
|
1081
|
-
fetchDependencies: nextFetchDependencies
|
|
1082
|
-
}
|
|
1083
|
-
));
|
|
1084
|
-
|
|
1085
|
-
}
|
|
1086
|
-
|
|
1087
|
-
console.groupEnd()
|
|
1088
|
-
|
|
1089
|
-
await Promise.all(apiRequestPromises)
|
|
1090
|
-
|
|
1091
|
-
apiRequestPromises.map(async (promise) => {
|
|
1092
|
-
if (!Array.isArray(request.fetchDependencies)) {
|
|
1093
|
-
request.fetchDependencies = [];
|
|
1094
|
-
}
|
|
1095
|
-
request.fetchDependencies.push(await promise)
|
|
1096
|
-
})
|
|
1097
|
-
|
|
1098
|
-
}
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
}
|
|
1102
|
-
|
|
1103
|
-
if (request.debug && isLocal) {
|
|
1104
|
-
|
|
1105
|
-
toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
|
|
1106
|
-
|
|
1107
|
-
}
|
|
1108
|
-
|
|
1109
|
-
return response;
|
|
1110
|
-
|
|
1111
|
-
}
|
|
1112
|
-
)
|
|
1113
|
-
;
|
|
1114
|
-
|
|
1115
|
-
} catch
|
|
1116
|
-
(error) {
|
|
1117
|
-
|
|
1118
|
-
if (isTest) {
|
|
1119
|
-
|
|
1120
|
-
throw new Error(JSON.stringify(error))
|
|
1121
|
-
|
|
1122
|
-
}
|
|
1123
|
-
|
|
1124
|
-
console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000')
|
|
1125
|
-
|
|
1126
|
-
console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0')
|
|
1127
|
-
|
|
1128
|
-
console.warn(error)
|
|
1129
|
-
|
|
1130
|
-
console.trace()
|
|
1131
|
-
|
|
1132
|
-
console.groupEnd()
|
|
1133
|
-
|
|
1134
|
-
TestRestfulResponse(error, request?.success, request?.error || "An restful API error occurred!")
|
|
1135
|
-
|
|
1136
|
-
return null;
|
|
1137
|
-
|
|
1138
|
-
}
|
|
1139
|
-
|
|
27
|
+
// SQL path if on Node with a provided pool
|
|
28
|
+
if (isNode && config.mysqlPool) {
|
|
29
|
+
const {SqlExecutor} = await import('./executors/SqlExecutor');
|
|
30
|
+
const executor = new SqlExecutor<CustomAndRequiredFields, RestTableInterfaces, RequestTableOverrides, ResponseDataType, RestShortTableNames>(config, request);
|
|
31
|
+
return executor.execute();
|
|
1140
32
|
}
|
|
1141
33
|
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
34
|
+
// HTTP path fallback
|
|
35
|
+
const {HttpExecutor} = await import('./executors/HttpExecutor');
|
|
36
|
+
const http = new HttpExecutor<CustomAndRequiredFields, RestTableInterfaces, RequestTableOverrides, ResponseDataType, RestShortTableNames>(config, request);
|
|
37
|
+
return http.execute();
|
|
38
|
+
};
|
|
1146
39
|
}
|
|
1147
|
-
|