generated from oracle/template-repo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
OracleTransform.js
1674 lines (1544 loc) · 50.9 KB
/
OracleTransform.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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2023, Oracle and/or its affiliates.
// Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
import log from '../../../logger';
import _ from 'lodash';
const Utils = require('../../../Utils');
var Parse = require('parse/node').Parse;
const transformKey = (className, fieldName, schema) => {
// Check if the schema is known since it's a built-in field.
switch (fieldName) {
case 'objectId':
return '_id';
case 'createdAt':
//CDB
//return '_created_at';
return 'createdAt';
//CDB-END
case 'updatedAt':
//CDB
//return '_updated_at';
return 'updatedAt';
//CDB-END
case 'sessionToken':
return '_session_token';
case 'lastUsed':
return '_last_used';
case 'timesUsed':
return 'times_used';
}
if (schema.fields[fieldName] && schema.fields[fieldName].__type == 'Pointer') {
fieldName = '_p_' + fieldName;
} else if (schema.fields[fieldName] && schema.fields[fieldName].type == 'Pointer') {
fieldName = '_p_' + fieldName;
}
return fieldName;
};
const valueAsDate = value => {
if (typeof value === 'string') {
return new Date(value);
} else if (value instanceof Date) {
return value;
}
return false;
};
const isRegex = value => {
return value && value instanceof RegExp;
};
const isStartsWithRegex = value => {
if (!isRegex(value)) {
return false;
}
const matches = value.toString().match(/\/\^\\Q.*\\E\//);
return !!matches;
};
const isAllValuesRegexOrNone = values => {
if (!values || !Array.isArray(values) || values.length === 0) {
return true;
}
const firstValuesIsRegex = isStartsWithRegex(values[0]);
if (values.length === 1) {
return firstValuesIsRegex;
}
for (let i = 1, length = values.length; i < length; ++i) {
if (firstValuesIsRegex !== isStartsWithRegex(values[i])) {
return false;
}
}
return true;
};
const isAnyValueRegex = values => {
return values.some(function (value) {
return isRegex(value);
});
};
// Transforms a query constraint from REST API format to Mongo format.
// A constraint is something with fields like $lt.
// If it is not a valid constraint but it could be a valid something
// else, return CannotTransform.
// inArray is whether this is an array field.
function transformConstraint(constraint, field, count = false) {
const inArray = field && field.type && field.type === 'Array';
if (typeof constraint !== 'object' || !constraint) {
return CannotTransform;
}
const transformFunction = inArray ? transformInteriorAtom : transformTopLevelAtom;
const transformer = atom => {
const result = transformFunction(atom, field);
if (result === CannotTransform) {
throw new Parse.Error(Parse.Error.INVALID_JSON, `bad atom: ${JSON.stringify(atom)}`);
}
return result;
};
// keys is the constraints in reverse alphabetical order.
// This is a hack so that:
// $regex is handled before $options
// $nearSphere is handled before $maxDistance
var keys = Object.keys(constraint).sort().reverse();
var answer = {};
for (var key of keys) {
switch (key) {
case '$lt':
case '$lte':
case '$gt':
case '$gte':
case '$exists':
case '$ne':
case '$eq': {
const val = constraint[key];
if (val && typeof val === 'object' && val.$relativeTime) {
if (field && field.type !== 'Date') {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'$relativeTime can only be used with Date field'
);
}
switch (key) {
case '$exists':
case '$ne':
case '$eq':
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'$relativeTime can only be used with the $lt, $lte, $gt, and $gte operators'
);
}
const parserResult = Utils.relativeTimeToDate(val.$relativeTime);
if (parserResult.status === 'success') {
answer[key] = parserResult.result;
break;
}
log.info('Error while parsing relative date', parserResult);
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`bad $relativeTime (${key}) value. ${parserResult.info}`
);
}
answer[key] = DateCoder.DatabaseToJSON(transformer(val));
break;
}
case '$in':
case '$nin': {
const arr = constraint[key];
if (!(arr instanceof Array)) {
throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad ' + key + ' value');
}
answer[key] = _.flatMap(arr, value => {
return (atom => {
if (Array.isArray(atom)) {
return value.map(transformer);
} else {
return transformer(atom);
}
})(value);
});
break;
}
case '$all': {
const arr = constraint[key];
if (!(arr instanceof Array)) {
throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad ' + key + ' value');
}
answer[key] = arr.map(transformInteriorAtom);
const values = answer[key];
//CDB :Here should be fixed $all: [regex]
if (isAnyValueRegex(values) && !isAllValuesRegexOrNone(values)) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'All $all values must be of regex type or none: ' + values
);
}
if (isAnyValueRegex(values) && isAllValuesRegexOrNone(values)) {
// Transform in $and : field: regex[i]
// { "$and" : [ {"FIELD": {"$regex":"VALUE[i]"}}, {"FIELD": {"$regex":"VALUE[i+1]"}}.... }]}
const transformedKeys = [];
let transformedKey = {};
for (var reg of values) {
let s = reg.valueOf().toString();
s = s.replace('\\Q', '(');
s = s.replace('\\E', ')');
if (s[0] == '/' && s[s.length - 1] == '/') {
s = s.substring(1, s.length - 1);
}
transformedKey = {
//Distinguished field name
'__FIELD__!!__': {
$regex: s,
},
};
//transformedKey = s;
transformedKeys.push(transformedKey);
}
answer[key] = transformedKeys;
}
return answer;
//CDB-END
}
case '$regex': {
var s = constraint[key];
if (typeof s !== 'string') {
throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad regex: ' + s);
}
//CDB
// manage "$options":
let exit = false;
if (keys.length == 2) {
if (keys[1] == '$options') {
var options = constraint['$options'];
if (options.indexOf('m') != -1) {
//: "m" --> for "$regex" add multiline search
s = '((.|\n)*)' + s + '((.|\n)*)';
answer = {};
answer['$regex'] = s;
exit = true;
}
if (options.indexOf('i') != -1) {
//: "i" --> for "$regex" add "$upper" and set the string to UPPERCASE
answer = {};
answer['$lower'] = { $regex: s.toLowerCase() };
exit = true;
}
}
}
if (exit) {
break;
}
//CDB-END
//CDB
// MANAGE endsWith('$')
const special = '\\,.?{}[]()$^*\'+@|"';
if (s[s.length - 1] == '$' && s[s.length - 2] == 'E' && s[s.length - 3] == '\\') {
s = s.replace('\\E\\\\E\\Q', '\\E');
s = s.replace('\\Q', '.*');
s = s.replace('\\E$', '$');
let t = s.substring(2, s.length - 1);
for (const i in special) {
t = t.replaceAll(special[i], '\\' + special[i]);
}
s = '.*' + t + '$';
// To distinguish a normal 'matches regex' or 'matches string' from StartsWith or EndWith or Contains
//} else if (s[0] == '^') {
} else if (s[0] == '^' && s.indexOf('\\E\\\\E\\Q') != -1) {
// MANAGE startsWith('^')
s = s.replace('\\E\\\\E\\Q', '\\E');
s = s.replace('\\Q', '');
let t = s.substring(1, s.length - 2);
for (const i in special) {
t = t.replaceAll(special[i], '\\' + special[i]);
}
s = '^' + t + '.*';
// To distinguish a normal 'matches regex' or 'matches string' from StartsWith or EndWith or Contains
//} else {
} else if (s.indexOf('\\E\\\\E\\Q') != -1) {
// MANAGE contains('.*')
s = s.replace('\\E\\\\E\\Q', '\\E');
s = s.replace('\\Q', '.*');
let t = s.substring(2, s.length - 2);
for (const i in special) {
t = t.replaceAll(special[i], '\\' + special[i]);
}
s = '.*' + t + '.*';
}
// to managed 'nested contains'
if (s.substring(0, 2) == '\\Q' && s.substring(s.length - 2, s.length) == '\\E') {
s = s.replace('\\Q', '.*');
s = s.replace('\\E', '.*');
}
answer[key] = s;
//CDB-END
break;
}
case '$containedBy': {
const arr = constraint[key];
if (!(arr instanceof Array)) {
throw new Parse.Error(Parse.Error.INVALID_JSON, `bad $containedBy: should be an array`);
}
//CDB
/*
answer.$elemMatch = {
$nin: arr.map(transformer)
};
*/
answer['$in'] = arr;
//CDB-END
break;
}
case '$options':
//CDB
if (typeof answer['$lower'] === 'undefined') {
answer[key] = constraint[key];
}
//CDB-END
break;
case '$text': {
const search = constraint[key].$search;
if (typeof search !== 'object') {
throw new Parse.Error(Parse.Error.INVALID_JSON, `bad $text: $search, should be object`);
}
if (!search.$term || typeof search.$term !== 'string') {
throw new Parse.Error(Parse.Error.INVALID_JSON, `bad $text: $term, should be string`);
} else {
answer[key] = {
$search: search.$term,
};
}
if (search.$language && typeof search.$language !== 'string') {
throw new Parse.Error(Parse.Error.INVALID_JSON, `bad $text: $language, should be string`);
} else if (search.$language) {
answer[key].$language = search.$language;
}
if (search.$caseSensitive && typeof search.$caseSensitive !== 'boolean') {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`bad $text: $caseSensitive, should be boolean`
);
} else if (search.$caseSensitive) {
answer[key].$caseSensitive = search.$caseSensitive;
}
if (search.$diacriticSensitive && typeof search.$diacriticSensitive !== 'boolean') {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`bad $text: $diacriticSensitive, should be boolean`
);
} else if (search.$diacriticSensitive) {
answer[key].$diacriticSensitive = search.$diacriticSensitive;
}
break;
}
case '$nearSphere': {
const point = constraint[key];
var temp;
if (count) {
answer.$geoWithin = {
$centerSphere: [[point.longitude, point.latitude], constraint.$maxDistance],
};
} else {
if (typeof constraint['$maxDistance'] === 'undefined') {
/*
For Mongo, $maxDistance default is not sepcified in the docs afaik
The behavior seems to be all points
I am defaulting maxDistance to 10000 miles
*/
temp = `{"$geometry": {"type": "Point","coordinates": [${point.longitude},${point.latitude}]},"$distance": 10000,"$unit": "mile"}`;
} else {
/* Waiting on Radians fix, this query doesn't work 12/13/22
{"construct": "line","location": {"$near": {"$geometry": {"type": "Point","coordinates": [19,24]},"$distance": 2.526,"$unit": "radian"}}}
Parse seems to prefer radians, check out ParseQuery.js withinMiles
*/
const distance = constraint['$maxDistance'] * 3958.8;
temp = `{"$geometry": {"type": "Point","coordinates": [${point.longitude},${point.latitude}]},"$distance": ${distance},"$unit": "mile"}`;
}
answer['$near'] = JSON.parse(temp);
}
break;
}
case '$maxDistance': {
// Not Supported
/* if (count) {
break;
}
answer[key] = constraint[key];*/
break;
}
// The SDKs don't seem to use these but they are documented in the
// REST API docs.
case '$maxDistanceInRadians':
answer['$maxDistance'] = constraint[key];
break;
case '$maxDistanceInMiles':
answer['$maxDistance'] = constraint[key] / 3959;
break;
case '$maxDistanceInKilometers':
answer['$maxDistance'] = constraint[key] / 6371;
break;
case '$select':
case '$dontSelect':
throw new Parse.Error(
Parse.Error.COMMAND_UNAVAILABLE,
'the ' + key + ' constraint is not supported yet'
);
case '$within':
var box = constraint[key]['$box'];
if (!box || box.length != 2) {
throw new Parse.Error(Parse.Error.INVALID_JSON, 'malformatted $within arg');
}
var boxcoords = {
type: 'Polygon',
coordinates: [
[
[box[0].longitude, box[0].latitude],
[box[0].longitude, box[1].latitude],
[box[1].longitude, box[0].latitude],
[box[1].longitude, box[1].latitude],
[box[0].longitude, box[0].latitude],
],
],
};
var geometry = { $geometry: boxcoords };
answer[key] = geometry;
break;
case '$geoWithin': {
const polygon = constraint[key]['$polygon'];
const centerSphere = constraint[key]['$centerSphere'];
if (polygon !== undefined) {
let points;
if (typeof polygon === 'object' && polygon.__type === 'Polygon') {
if (!polygon.coordinates || polygon.coordinates.length < 3) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'bad $geoWithin value; Polygon.coordinates should contain at least 3 lon/lat pairs'
);
}
points = polygon.coordinates;
} else if (polygon instanceof Array) {
if (polygon.length < 3) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'bad $geoWithin value; $polygon should contain at least 3 GeoPoints'
);
}
points = polygon;
} else {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
"bad $geoWithin value; $polygon should be Polygon object or Array of Parse.GeoPoint's"
);
}
points = points.map(point => {
if (point instanceof Array && point.length === 2) {
Parse.GeoPoint._validate(point[1], point[0]);
return point;
}
if (!GeoPointCoder.isValidJSON(point)) {
throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad $geoWithin value');
} else {
Parse.GeoPoint._validate(point.latitude, point.longitude);
}
return [point.longitude, point.latitude];
});
// Test if polygon points are open. If so, add closing point
if (JSON.stringify(points[0]) !== JSON.stringify(points[points.length - 1])) {
points.push(points[0]);
}
var coords = {
type: 'Polygon',
coordinates: [points],
};
var poly = { $geometry: coords };
answer['$within'] = poly;
} else if (centerSphere !== undefined) {
if (!(centerSphere instanceof Array) || centerSphere.length < 2) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'bad $geoWithin value; $centerSphere should be an array of Parse.GeoPoint and distance'
);
}
// Get point, convert to geo point if necessary and validate
let point = centerSphere[0];
if (point instanceof Array && point.length === 2) {
point = new Parse.GeoPoint(point[1], point[0]);
} else if (!GeoPointCoder.isValidJSON(point)) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'bad $geoWithin value; $centerSphere geo point invalid'
);
}
Parse.GeoPoint._validate(point.latitude, point.longitude);
// Get distance and validate
const distance = centerSphere[1];
if (isNaN(distance) || distance < 0) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'bad $geoWithin value; $centerSphere distance invalid'
);
}
answer[key] = {
$centerSphere: [[point.longitude, point.latitude], distance],
};
}
break;
}
case '$geoIntersects': {
const point = constraint[key]['$point'];
if (!GeoPointCoder.isValidJSON(point)) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
'bad $geoIntersect value; $point should be GeoPoint'
);
} else {
Parse.GeoPoint._validate(point.latitude, point.longitude);
}
answer[key] = {
$geometry: {
type: 'Point',
coordinates: [point.longitude, point.latitude],
},
};
// Use Oracle Operator $intersects
answer['$intersects'] = answer['$geoIntersects'];
delete answer['$geoIntersects'];
break;
}
default:
if (key.match(/^\$+/)) {
throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad constraint: ' + key);
}
return CannotTransform;
}
}
return answer;
}
const nestedOracleObjectToNestedParseObject = oracleObject => {
switch (typeof oracleObject) {
case 'string':
case 'number':
case 'boolean':
case 'undefined':
return oracleObject;
case 'symbol':
case 'function':
throw 'bad value in nestedOracleObjectToNestedParseObject';
case 'object':
if (oracleObject === null) {
return null;
}
if (oracleObject instanceof Array) {
return oracleObject.map(nestedOracleObjectToNestedParseObject);
}
if (oracleObject instanceof Date) {
return Parse._encode(oracleObject);
}
// if (oracleObject instanceof mongodb.Long) {
// return oracleObject.toNumber();
// }
// if (oracleObject instanceof mongodb.Double) {
// return oracleObject.value;
// }
if (BytesCoder.isValidDatabaseObject(oracleObject)) {
return BytesCoder.databaseToJSON(oracleObject);
}
if (
Object.prototype.hasOwnProperty.call(oracleObject, '__type') &&
oracleObject.__type == 'Date' &&
oracleObject.iso instanceof Date
) {
oracleObject.iso = oracleObject.iso.toJSON();
return oracleObject;
}
return mapValues(oracleObject, nestedOracleObjectToNestedParseObject);
default:
throw 'unknown js type';
}
};
function transformQueryKeyValue(className, key, value, schema, count = false) {
switch (key) {
case 'createdAt':
//if (valueAsDate(value)) {
// return { key: '_created_at', value: valueAsDate(value) };
//}
//CDB
if (!(value[Object.keys(value)[0]].iso == undefined)) {
const operator = Object.keys(value)[0];
return {
key: 'createdAt',
value: { $timestamp: { [operator]: valueAsDate(value[Object.keys(value)[0]].iso) } },
};
} else if (valueAsDate(value)) {
return {
key: '_created_at',
value: valueAsDate(value),
};
}
//CDB-END
key = '_created_at';
break;
case 'updatedAt':
if (valueAsDate(value)) {
return {
//CDB
//key: '_updated_at',
key: 'updatedAt',
//CDB-END
value: valueAsDate(value),
};
}
key = '_updated_at';
break;
case 'expiresAt':
if (valueAsDate(value)) {
return { key: 'expiresAt', value: valueAsDate(value) };
}
break;
case '_email_verify_token_expires_at':
if (valueAsDate(value)) {
return {
key: '_email_verify_token_expires_at',
value: valueAsDate(value),
};
}
break;
case 'objectId': {
if (['_GlobalConfig', '_GraphQLConfig'].includes(className)) {
value = parseInt(value);
}
return { key: '_id', value };
}
case '_account_lockout_expires_at':
if (valueAsDate(value)) {
return {
key: '_account_lockout_expires_at',
value: valueAsDate(value),
};
}
break;
case '_failed_login_count':
return { key, value };
case 'sessionToken':
return { key: '_session_token', value };
case '_perishable_token_expires_at':
if (valueAsDate(value)) {
return {
key: '_perishable_token_expires_at',
value: valueAsDate(value),
};
}
break;
case '_password_changed_at':
if (valueAsDate(value)) {
return { key: '_password_changed_at', value: valueAsDate(value) };
}
break;
case '_rperm':
case '_wperm':
case '_perishable_token':
case '_email_verify_token':
return { key, value };
case '$or':
case '$and':
case '$nor':
return {
key: key,
value: value.map(subQuery => transformWhere(className, subQuery, schema, count)),
};
case 'lastUsed':
if (valueAsDate(value)) {
return { key: '_last_used', value: valueAsDate(value) };
}
key = '_last_used';
break;
case 'timesUsed':
return { key: 'times_used', value: value };
default: {
// Other auth data
const authDataMatch = key.match(/^authData\.([a-zA-Z0-9_]+)\.id$/);
if (authDataMatch) {
const provider = authDataMatch[1];
// Special-case auth data.
return { key: `_auth_data_${provider}.id`, value };
}
}
}
const expectedTypeIsArray = schema && schema.fields[key] && schema.fields[key].type === 'Array';
const expectedTypeIsPointer =
schema && schema.fields[key] && schema.fields[key].type === 'Pointer';
const field = schema && schema.fields[key];
if (
expectedTypeIsPointer ||
(!schema && !key.includes('.') && value && value.__type === 'Pointer')
) {
key = '_p_' + key;
}
// Handle query constraints
const transformedConstraint = transformConstraint(value, field, count);
if (transformedConstraint !== CannotTransform) {
if (transformedConstraint.$text) {
return { key: '$text', value: transformedConstraint.$text };
}
if (transformedConstraint.$elemMatch) {
return { key: '$nor', value: [{ [key]: transformedConstraint }] };
}
return { key, value: transformedConstraint };
}
if (expectedTypeIsArray && !(value instanceof Array)) {
return { key, value: { $all: [transformInteriorAtom(value)] } };
}
// Handle atomic values
const transformRes = key.includes('.')
? transformInteriorAtom(value)
: transformTopLevelAtom(value);
if (transformRes !== CannotTransform) {
return { key, value: transformRes };
} else {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`You cannot use ${value} as a query parameter.`
);
}
}
// Main exposed method to help run queries.
// restWhere is the "where" clause in REST API form.
// Returns the oracle form of the query.
function transformWhere(className, restWhere, schema, count = false) {
const oracleWhere = {};
for (const restKey in restWhere) {
const out = transformQueryKeyValue(className, restKey, restWhere[restKey], schema, count);
oracleWhere[out.key] = out.value;
}
return oracleWhere;
}
const parseObjectKeyValueToOracleObjectKeyValue = (restKey, restValue, schema) => {
// Check if the schema is known since it's a built-in field.
let transformedValue;
switch (restKey) {
case 'objectId':
return { key: '_id', value: restValue };
case 'expiresAt':
transformedValue = transformTopLevelAtom(restValue);
return { key: 'expiresAt', value: transformedValue };
case '_email_verify_token_expires_at':
transformedValue = transformTopLevelAtom(restValue);
return { key: '_email_verify_token_expires_at', value: transformedValue };
case '_account_lockout_expires_at':
transformedValue = transformTopLevelAtom(restValue);
return { key: '_account_lockout_expires_at', value: transformedValue };
case '_perishable_token_expires_at':
transformedValue = transformTopLevelAtom(restValue);
return { key: '_perishable_token_expires_at', value: transformedValue };
case '_password_changed_at':
transformedValue = transformTopLevelAtom(restValue);
return { key: '_password_changed_at', value: transformedValue };
case '_failed_login_count':
case '_rperm':
case '_wperm':
case '_email_verify_token':
case '_hashed_password':
case '_perishable_token':
return { key: restKey, value: restValue };
case 'sessionToken':
return { key: '_session_token', value: restValue };
default:
// Auth data should have been transformed already
if (restKey.match(/^authData\.([a-zA-Z0-9_]+)\.id$/)) {
throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, 'can only query on ' + restKey);
}
// Trust that the auth data has been transformed and save it directly
if (restKey.match(/^_auth_data_[a-zA-Z0-9_]+$/)) {
return { key: restKey, value: restValue };
}
}
//skip straight to transformTopLevelAtom for Bytes, they don't show up in the schema for some reason
if (restValue && restValue.__type !== 'Bytes') {
//Note: We may not know the type of a field here, as the user could be saving (null) to a field
//That never existed before, meaning we can't infer the type.
if (
(schema.fields[restKey] && schema.fields[restKey].type == 'Pointer') ||
restValue.__type == 'Pointer'
) {
restKey = '_p_' + restKey;
}
}
// Handle atomic values
var value = transformTopLevelAtom(restValue);
if (value !== CannotTransform) {
return { key: restKey, value: value };
}
// ACLs are handled before this method is called
// If an ACL key still exists here, something is wrong.
if (restKey === 'ACL') {
throw 'There was a problem transforming an ACL.';
}
// Handle arrays
if (restValue instanceof Array) {
value = restValue.map(transformInteriorValue);
return { key: restKey, value: value };
}
// Handle normal objects by recursing
if (Object.keys(restValue).some(key => key.includes('$') || key.includes('.'))) {
throw new Parse.Error(
Parse.Error.INVALID_NESTED_KEY,
"Nested keys should not contain the '$' or '.' characters"
);
}
value = mapValues(restValue, transformInteriorValue);
return { key: restKey, value };
};
const parseObjectToOracleObjectForCreate = (className, restCreate, schema) => {
restCreate = addLegacyACL(restCreate);
const oracleCreate = {};
for (const restKey in restCreate) {
if (restCreate[restKey] && restCreate[restKey].__type === 'Relation') {
continue;
}
const { key, value } = parseObjectKeyValueToOracleObjectKeyValue(
restKey,
restCreate[restKey],
schema
);
if (value !== undefined) {
oracleCreate[key] = value;
}
}
// // Use the legacy mongo format for createdAt and updatedAt
// if (mongoCreate.createdAt) {
// mongoCreate._created_at = new Date(mongoCreate.createdAt.iso || mongoCreate.createdAt);
// delete mongoCreate.createdAt;
// }
// if (mongoCreate.updatedAt) {
// mongoCreate._updated_at = new Date(mongoCreate.updatedAt.iso || mongoCreate.updatedAt);
// delete mongoCreate.updatedAt;
// }
return oracleCreate;
};
// Main exposed method to help update old objects.
const transformUpdate = (className, restUpdate, parseFormatSchema) => {
const oraUpdate = {};
const acl = addLegacyACL(restUpdate);
if (acl._rperm || acl._wperm || acl._acl) {
oraUpdate.$set = {};
if (acl._rperm) {
oraUpdate._rperm = acl._rperm;
}
if (acl._wperm) {
oraUpdate._wperm = acl._wperm;
}
if (acl._acl) {
oraUpdate._acl = acl._acl;
}
delete oraUpdate.$set;
}
for (var restKey in restUpdate) {
if (restUpdate[restKey] && restUpdate[restKey].__type === 'Relation') {
continue;
}
var out = transformKeyValueForUpdate(
className,
restKey,
restUpdate[restKey],
parseFormatSchema
);
// If the output value is an object with any $ keys, it's an
// operator that needs to be lifted onto the top level update
// object.
if (typeof out.value === 'object' && out.value !== null && out.value.__op) {
oraUpdate[out.value.__op] = oraUpdate[out.value.__op] || {};
oraUpdate[out.value.__op][out.key] = out.value.arg;
} else {
const dotNotation = out.key.split('.');
if (dotNotation.length === 2) {
// one level dot notation. This may need to be written for multiple levels
const newKey = dotNotation[1];
const newObj = new Object();
newObj[newKey] = out.value;
oraUpdate[dotNotation[0]] = newObj;
} else {
oraUpdate[out.key] = out.value;
}
}
}
return oraUpdate;
};
const transformKeyValueForUpdate = (className, restKey, restValue, parseFormatSchema) => {
// Check if the schema is known since it's a built-in field.
var key = restKey;
var timeField = false;
switch (key) {
case 'objectId':
case '_id':
if (['_GlobalConfig', '_GraphQLConfig'].includes(className)) {
return {
key: key,
value: parseInt(restValue),
};
}
key = '_id';
break;
case 'createdAt':
case '_created_at':
key = 'createdAt';
timeField = true;
break;
case 'updatedAt':
case '_updated_at':
key = 'updatedAt';
timeField = true;
break;
case 'sessionToken':
case '_session_token':
key = '_session_token';
break;
case 'expiresAt':
case '_expiresAt':
key = 'expiresAt';
timeField = true;
break;
case '_email_verify_token_expires_at':
key = '_email_verify_token_expires_at';
timeField = true;
break;
case '_account_lockout_expires_at':
key = '_account_lockout_expires_at';
timeField = true;
break;
case '_failed_login_count':
key = '_failed_login_count';
break;
case '_perishable_token_expires_at':
key = '_perishable_token_expires_at';
timeField = true;
break;
case '_password_changed_at':
key = '_password_changed_at';
timeField = true;
break;
case '_rperm':
case '_wperm':
return { key: key, value: restValue };
case 'lastUsed':
case '_last_used':
key = '_last_used';
timeField = true;
break;
case 'timesUsed':
case 'times_used':
key = 'times_used';
timeField = true;
break;
}
if (
(parseFormatSchema.fields[key] && parseFormatSchema.fields[key].type === 'Pointer') ||
(!key.includes('.') &&
!parseFormatSchema.fields[key] &&
restValue &&
restValue.__type == 'Pointer') // Do not use the _p_ prefix for pointers inside nested documents
) {
key = '_p_' + key;
}