-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuildRule.js
643 lines (529 loc) · 17.9 KB
/
buildRule.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
const flatten = require('flat');
const { operatorMap } = require("./constants");
const { convertGraphQLToFQL } = require("./graphqlToFQLConverter");
const {
capitalizeFirstLetter,
removeQuotes,
checkBool,
isNumeric,
removeSpaces
} = require("./helper");
let objectMap = new Map();
const factMap = new Map();
const conditionMap = new Map();
const existingVariablesMap = new Map();
const topLevel = new Map();
const functionCall = ' => ';
const prefix = 'RE_';
const requestBodyFact = {
"type": "Fact",
"name": "nationality",
"value": 'query User {author(where: {id: $id}) {nationality}}'
}
const requestBodyFact2 = {
"type": "Fact",
"name": "job",
"value": 'query User {posts(where: {id: "ckadqdbhk00go0148zzxh4bbq", name: "Micha", something: "bla"}) {job}}'
}
const requestBodyCondition = {
"type": "Condition",
"name": "isIncomeHigherThan2000",
"source": {
"type": "Fact",
"name": "income",
"value": 'query User {posts(where: {id: "ckadqdbhk00go0148zzxh4bbq", name: "Micha", something: "bla"}) {job}}'
},
"comparator": "gt",
"target": {
"type": "Number",
"value": 2000
}
}
const requestBody = {
"type": "Rule",
"name": "isEligibleForCredit",
"all": [
{
"type": "Condition",
"name": "isNationalityFrance",
"source": {
"type": "Fact",
"name": "nationality",
"value": 'query User {author(where: {id: "ckadqdbhk00go0148zzxh4bbq"}) {nationality}}'
},
"comparator": "eq",
"target": {
"type": "String",
"value": "France"
}
},
{
"any": [
{
"type": "Condition",
"name": "isIncomeHigherThan2000",
"source": {
"type": "Fact",
"name": "income",
"value": 'query User {posts(where: {id: $id, name: $name}) {income}}'
},
"comparator": "gt",
"target": {
"type": "Number",
"value": 2000
}
},
{
"type": "Condition",
"name": "hasJob",
"source": {
"type": "Fact",
"name": "job",
"value": 'query User {posts(where: {id: "ckadqdbhk00go0148zzxh4bbq", name: "Micha"}) {job}}'
},
"comparator": "eq",
"target": {
"type": "Boolean",
"value": true
}
},
{
"all": [
{
"type": "Condition",
"name": "isIncomeHigherThan2000",
"source": {
"type": "Fact",
"name": "income",
"value": 'query User {user(where: {id: "ckadqdbhk00go0148zzxh4bbq"}) {income}}'
},
"comparator": "gt",
"target": {
"type": "Number",
"value": 2000
}
},
{
"type": "Condition",
"name": "hasJob",
"source": {
"type": "Fact",
"name": "job",
"value": 'query User {user(where: {id: $id}) {job}}'
},
"comparator": "eq",
"target": {
"type": "Boolean",
"value": true
}
}
]
}
]
}
]
}
const getQueries = (data, queries) => {
if (!data)
return;
for (let index = 0; index < data.length; index++) {
const { all, any } = data[index];
if (all)
getQueries(all, queries);
else if (any)
getQueries(any, queries);
else {
const { source, target } = data[index];
if (source?.type?.toLowerCase() === 'fact')
queries.push(source.value);
if (target?.type?.toLowerCase() === 'fact')
queries.push(target.value);
}
}
}
const getCorrectOperator = (operator) => {
return operatorMap[operator.toLowerCase()] || operator;
}
const getTargetString = (operatorString, target) => {
const { type, value } = target;
if (type.toLowerCase() === 'fact')
return operatorString === '=='
? `${convertGraphQLToFQL(value)}`
: `(${convertGraphQLToFQL(value)})`;
else if (type.toLowerCase() === 'string')
return operatorString === '==' ? `"${value}"` : `("${value}")`
return value;
}
const build = (obj) => {
if (typeof obj !== "object" || obj === null) {
return 0;
}
const flatt = flatten(obj);
// console.log(flatt)
const flattMap = new Map(Object.entries(flatt));
const flattType = flatt.type;
const flattName = flatt.name;
switch (flattMap.get('type')) {
case 'Fact':
buildFact(obj)
break;
case 'Condition':
buildCondition(obj)
break;
case 'Rule':
buildRule(flattMap, flattType, flattName)
break;
}
}
const buildFact = (inputObject) => {
console.log(buildFactPart(inputObject))
}
const buildCondition = (inputObject) => {
const map = buildFactPart(inputObject.source)
console.log(buildConditionPart(map, inputObject))
}
const buildRule = (obj) => {
if (typeof obj !== "object" || obj === null) {
return 0;
}
const flat = flatten(obj);
// console.log(flat)
const map = new Map(Object.entries(flat));
createObjectMap(map)
// console.log(topLevel)
const ruleName = `${flat.type}${capitalizeFirstLetter(flat.name)}`
const ruleValue = createRule(topLevel)
const ruleMap = new Map([[ruleName, ruleValue]]);
console.log(objectMap);
console.log(factMap);
console.log(conditionMap);
console.log(ruleMap);
objectMap.forEach((value, key) =>{
console.log(createFunction(key, value))
})
factMap.forEach((value, key) =>{
console.log(createFunction(key, value))
})
ruleMap.forEach((value, key) =>{
console.log(createFunction(key, value))
})
}
//
// const buildRule = (flattMap, flattType, flattName) => {
//
// createObjectMap(flattMap, flattType, flattName)
//
// const ruleName = `${flattType}${capitalizeFirstLetter(flattName)}`
// const ruleValue = createRule(topLevel)
// const ruleMap = new Map([[ruleName, ruleValue]]);
//
// console.log(objectMap);
// console.log(factMap);
// console.log(conditionMap);
// console.log(ruleMap);
//
// objectMap.forEach((value, key) =>{
// console.log(createFunction(key, value))
// })
// factMap.forEach((value, key) =>{
// console.log(createFunction(key, value))
// })
// ruleMap.forEach((value, key) =>{
// console.log(createFunction(key, value))
// })
//
// }
const createRule = (inputMap) => {
const openBracket = '(';
const closeBracket = ')';
const [firstKey] = inputMap.keys();
const [lastKey] = [...inputMap].at(-1)
let oldKey = firstKey;
let updatedKey = firstKey;
let ruleString;
let counterBrackets = 0;
let allUsedVariables = new Set();
ruleString = openBracket;
counterBrackets++;
inputMap.forEach((value, key) => {
// create all udfs
const source = topLevel.get(key).get(`${key}.source`)
const comparator = topLevel.get(key).get(`${key}.comparator`)
const target = topLevel.get(key).get(`${key}.target`)
const {conditionName, variableNames} = buildParts(source, comparator, target)
allUsedVariables.add(variableNames);
// check for position
if (key === oldKey && key.length === oldKey.length) {
ruleString += `${conditionName}(${variableNames})`;
if (updatedKey.startsWith('all')) {
ruleString += ' && '
} else {
ruleString += ' || '
}
} else {
// get correct position from key
if (key.length !== oldKey.length) {
updatedKey = key.slice(oldKey.length + 1);
}
// add brackets and operator
// only if it's not the last key
if(key !== lastKey) {
ruleString += openBracket;
ruleString += `${conditionName}(${variableNames})`;
counterBrackets++;
if (updatedKey.startsWith('all')) {
ruleString += ' && '
} else {
ruleString += ' || '
}
} else {
ruleString += `${conditionName}(${variableNames})`;
}
}
// console.log(key)
// console.log(oldKey)
// console.log(updatedKey)
// console.log(lastKey)
// console.log('----------------')
// console.log(ruleString)
// console.log('----------------')
oldKey = key;
})
// add the correct amount of brackets
const brackets = closeBracket.repeat(counterBrackets);
ruleString += brackets
return `(${[...allUsedVariables].flat().join(',')})${functionCall}${ruleString}`
}
const createObjectMap = (data) => {
let tempMidMap = new Map();
let tempLowerObject = {};
let oldName = Array.from(data.keys())[2].split('.');
oldName.pop();
oldName = oldName.join('.');
for (const [key, value] of data.entries()) {
const keys = key.split('.');
keys.pop();
const updatedAmount = keys.length;
const updatedKey = keys[updatedAmount-1];
const updatedName = keys.join('.');
const checkName = key.slice(0, updatedName.length)
const valueName = key.slice(updatedName.length + 1, key.length)
if (updatedKey !== undefined) {
if (isNumeric(updatedKey)) {
// Set subobjects to top lvl map
if (checkName === updatedName) {
topLevel.set(updatedName, tempMidMap);
}
// Set comparator map
if (valueName === 'comparator') {
// tempLowerObject = new Map([[valueName, value]])
tempLowerObject = {[valueName] : value};
tempMidMap.set(key, tempLowerObject);
}
} else {
if (checkName === updatedName) {
// Set or updated submaps
if (oldName !== updatedName) {
// tempLowerObject = new Map([[valueName, value]]);
tempLowerObject = {[valueName] : value};
tempMidMap.set(updatedName, tempLowerObject);
} else {
// tempLowerObject.set(valueName, value);
tempLowerObject[valueName] = value;
tempMidMap = new Map([[updatedName, tempLowerObject]]);
}
}
}
}
// necessary for usage of old/new map
oldName = updatedName !== '' || updatedName !== undefined ? updatedName : oldName;
}
}
const buildFactPart = (source) => {
const sourceString = convertGraphQLToFQL(source.value);
const collection = sourceString.split('.')[0];
// Create function name - Object
const udfSplit = sourceString.split('.');
udfSplit.pop()
let object = udfSplit.join('.');
let searchParamSplit = object.split('(');
searchParamSplit = searchParamSplit.at(searchParamSplit.length - 1).split(' ');
const searchParams = [];
const variableNames = [];
const fixedValues = [];
searchParamSplit.forEach(searchParamPart => {
if(searchParamPart.includes('.')) {
searchParams.push(capitalizeFirstLetter(searchParamPart.substring(2)));
} else if (searchParamPart.includes('&&')) {
searchParams.push('And');
} else if (searchParamPart.includes('$')) {
let tempName = searchParamPart.replace('$', '');
tempName = tempName.replace(')', '');
tempName = `${collection}${capitalizeFirstLetter(tempName)}`;
variableNames.push(tempName);
} else if (searchParamPart.includes('"')) {
fixedValues.push(
searchParamPart.replaceAll('"', '').replaceAll(')', '')
);
}
})
let objectName = `${udfSplit[0]}By`;
let index = 0;
searchParams.forEach(param => {
objectName += param
// If gql contains fixed value
// Add dynamically the value to name
if(fixedValues.length > 0) {
if (index === 0) {
objectName += `-${fixedValues[index++]}`;
} else if (param !== 'And') {
objectName += `-${fixedValues[index++]}`;
}
}
})
objectName = removeSpaces(objectName);
// Create function names - Fact
let factName = sourceString.split('.');
const collectionCapitalized = capitalizeFirstLetter(factName[0]);
const sourceType = capitalizeFirstLetter(factName[factName.length-1]);
factName = `fact${collectionCapitalized}${sourceType}`;
// Check for variable usage in gql query
let factValue = sourceString.split('.')
factValue = factValue[factValue.length-1]
let fact;
if (variableNames.size === 0) {
object = `()${functionCall}${object}`;
fact = `()${functionCall}${objectName}().${factValue}`;
} else {
const updatedVariableName = variableNames.join(',');
const updatedObject = object.replaceAll('$', '')
object = `(${updatedVariableName})${functionCall}${updatedObject}`;
fact = `(${updatedVariableName})${functionCall}${objectName}(${updatedVariableName}).${factValue}`;
// push only if it's a variable
existingVariablesMap.set(objectName, object);
}
const resultMap = new Map();
resultMap.set('object', {[objectName]: object})
resultMap.set('fact', {[factName]: fact})
resultMap.set('variable', variableNames);
return resultMap;
}
const buildConditionPart = (inputMap, inputObject) => {
const comparatorString = inputObject.comparator;
const source = inputObject.source;
const target = inputObject.target;
const operatorString = getCorrectOperator(comparatorString);
const targetString = getTargetString(operatorString, target);
const objectObject = inputMap.get('object');
let objectName = Object.keys(objectObject)[0];
let object = objectObject[objectName];
const factObject = inputMap.get('fact');
let factName = Object.keys(factObject)[0];
let factValue = factObject[factName];
const variableNames = inputMap.get('variable');
const collection = objectName.split('By')[0];
const collectionCapitalized = capitalizeFirstLetter(collection);
const sourceType = capitalizeFirstLetter(source.name);
// Create function names - Condition
const formattedComparator = capitalizeFirstLetter(comparatorString);
const formattedTarget = capitalizeFirstLetter(removeQuotes(targetString));
let conditionName;
if (checkBool(target)) {
conditionName = target.value ? `condition${collectionCapitalized}Has${sourceType}` : `condition${collectionCapitalized}HasNo${sourceType}`;
} else {
conditionName = `condition${collectionCapitalized}${sourceType}${formattedComparator}${formattedTarget}`;
}
let fact;
let condition;
if (variableNames.size === 0) {
condition = `()${functionCall}${factName}() ${operatorString} ${targetString}`;
} else {
const updatedVariableName = variableNames.join(',');
condition = `(${updatedVariableName})${functionCall}${factName}(${updatedVariableName}) ${operatorString} ${targetString}`;
// push only if it's a variable
}
const resultMap = new Map();
resultMap.set('object', {[objectName]: object})
resultMap.set('fact', {[factName]: factValue})
resultMap.set('condition', {[conditionName]: condition});
return resultMap;
}
const buildParts = (source, comparator, target) => {
const comparatorString = comparator.comparator;
const sourceString = convertGraphQLToFQL(source.value);
const operatorString = getCorrectOperator(comparatorString);
const targetString = getTargetString(operatorString, target);
const collection = sourceString.split('.')[0];
// Create function name - Object
const udfSplit = sourceString.split('.');
udfSplit.pop()
let object = udfSplit.join('.');
let searchParamSplit = object.split('(');
searchParamSplit = searchParamSplit.at(searchParamSplit.length - 1).split(' ');
const searchParams = []
const variableNames = [];
searchParamSplit.forEach(searchParamPart => {
if(searchParamPart.includes('.')) {
searchParams.push(capitalizeFirstLetter(searchParamPart.substring(1)));
} else if (searchParamPart.includes('&&')) {
searchParams.push('And');
} else if (searchParamPart.includes('$')) {
let tempName = searchParamPart.replace('$', '');
tempName = tempName.replace(')', '');
tempName = `${collection}${capitalizeFirstLetter(tempName)}`;
variableNames.push(tempName);
}
})
let objectName = `${udfSplit[0]}By${searchParams.join('')}`;
objectName = removeSpaces(objectName);
// Create function names - Fact
let factName = sourceString.split('.');
const collectionCapitalized = capitalizeFirstLetter(factName[0]);
const sourceType = capitalizeFirstLetter(factName[factName.length-1]);
factName = `fact${collectionCapitalized}${sourceType}`;
// Create function names - Condition
const formattedComparator = capitalizeFirstLetter(comparatorString);
const formattedTarget = capitalizeFirstLetter(removeQuotes(targetString));
let conditionName;
if (checkBool(target)) {
conditionName = target.value ? `condition${collectionCapitalized}Has${sourceType}` : `condition${collectionCapitalized}HasNo${sourceType}`;
} else {
conditionName = `condition${collectionCapitalized}${sourceType}${formattedComparator}${formattedTarget}`;
}
let fact;
let condition;
// Check for variable usage in gql query
let factValue = sourceString.split('.')
factValue = factValue[factValue.length-1]
if (variableNames.size === 0) {
object = `()${functionCall}${object}`;
fact = `()${functionCall}${objectName}().${factValue}`;
condition = `()${functionCall}${factName}() ${operatorString} ${targetString}`;
} else {
const updatedVariableName = variableNames.join(',');
const updatedObject = object.replaceAll('$', '')
object = `(${updatedVariableName})${functionCall}${updatedObject}`;
fact = `(${updatedVariableName})${functionCall}${objectName}(${updatedVariableName}).${factValue}`;
condition = `(${updatedVariableName})${functionCall}${factName}(${updatedVariableName}) ${operatorString} ${targetString}`;
// push only if it's a variable
existingVariablesMap.set(objectName, object);
}
if(existingVariablesMap.has(objectName)) {
objectMap.set(objectName, existingVariablesMap.get(objectName));
} else {
objectMap.set(objectName, object);
}
factMap.set(factName, fact)
conditionMap.set(conditionName, condition);
return { conditionName, condition, variableNames };
}
const createFunction = (functionName, functionBody) => {
return `Function.create({
name: '${functionName}',
body: '${functionBody}'
})`
}
buildRule(requestBody)
// build(requestBodyFact)
// build(requestBodyFact2)
// build(requestBodyCondition)