-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
SchemaController.js
1603 lines (1492 loc) · 50.3 KB
/
SchemaController.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
// @flow
// This class handles schema validation, persistence, and modification.
//
// Each individual Schema object should be immutable. The helpers to
// do things with the Schema just return a new schema when the schema
// is changed.
//
// The canonical place to store this Schema is in the database itself,
// in a _SCHEMA collection. This is not the right way to do it for an
// open source framework, but it's backward compatible, so we're
// keeping it this way for now.
//
// In API-handling code, you should only use the Schema class via the
// DatabaseController. This will let us replace the schema logic for
// different databases.
// TODO: hide all schema logic inside the database adapter.
// @flow-disable-next
const Parse = require('parse/node').Parse;
import { StorageAdapter } from '../Adapters/Storage/StorageAdapter';
import SchemaCache from '../Adapters/Cache/SchemaCache';
import DatabaseController from './DatabaseController';
import Config from '../Config';
// @flow-disable-next
import deepcopy from 'deepcopy';
import type {
Schema,
SchemaFields,
ClassLevelPermissions,
SchemaField,
LoadSchemaOptions,
} from './types';
const defaultColumns: { [string]: SchemaFields } = Object.freeze({
// Contain the default columns for every parse object type (except _Join collection)
_Default: {
objectId: { type: 'String' },
createdAt: { type: 'Date' },
updatedAt: { type: 'Date' },
ACL: { type: 'ACL' },
},
// The additional default columns for the _User collection (in addition to DefaultCols)
_User: {
username: { type: 'String' },
password: { type: 'String' },
email: { type: 'String' },
emailVerified: { type: 'Boolean' },
authData: { type: 'Object' },
},
// The additional default columns for the _Installation collection (in addition to DefaultCols)
_Installation: {
installationId: { type: 'String' },
deviceToken: { type: 'String' },
channels: { type: 'Array' },
deviceType: { type: 'String' },
pushType: { type: 'String' },
GCMSenderId: { type: 'String' },
timeZone: { type: 'String' },
localeIdentifier: { type: 'String' },
badge: { type: 'Number' },
appVersion: { type: 'String' },
appName: { type: 'String' },
appIdentifier: { type: 'String' },
parseVersion: { type: 'String' },
},
// The additional default columns for the _Role collection (in addition to DefaultCols)
_Role: {
name: { type: 'String' },
users: { type: 'Relation', targetClass: '_User' },
roles: { type: 'Relation', targetClass: '_Role' },
},
// The additional default columns for the _Session collection (in addition to DefaultCols)
_Session: {
user: { type: 'Pointer', targetClass: '_User' },
installationId: { type: 'String' },
sessionToken: { type: 'String' },
expiresAt: { type: 'Date' },
createdWith: { type: 'Object' },
},
_Product: {
productIdentifier: { type: 'String' },
download: { type: 'File' },
downloadName: { type: 'String' },
icon: { type: 'File' },
order: { type: 'Number' },
title: { type: 'String' },
subtitle: { type: 'String' },
},
_PushStatus: {
pushTime: { type: 'String' },
source: { type: 'String' }, // rest or webui
query: { type: 'String' }, // the stringified JSON query
payload: { type: 'String' }, // the stringified JSON payload,
title: { type: 'String' },
expiry: { type: 'Number' },
expiration_interval: { type: 'Number' },
status: { type: 'String' },
numSent: { type: 'Number' },
numFailed: { type: 'Number' },
pushHash: { type: 'String' },
errorMessage: { type: 'Object' },
sentPerType: { type: 'Object' },
failedPerType: { type: 'Object' },
sentPerUTCOffset: { type: 'Object' },
failedPerUTCOffset: { type: 'Object' },
count: { type: 'Number' }, // tracks # of batches queued and pending
},
_JobStatus: {
jobName: { type: 'String' },
source: { type: 'String' },
status: { type: 'String' },
message: { type: 'String' },
params: { type: 'Object' }, // params received when calling the job
finishedAt: { type: 'Date' },
},
_JobSchedule: {
jobName: { type: 'String' },
description: { type: 'String' },
params: { type: 'String' },
startAfter: { type: 'String' },
daysOfWeek: { type: 'Array' },
timeOfDay: { type: 'String' },
lastRun: { type: 'Number' },
repeatMinutes: { type: 'Number' },
},
_Hooks: {
functionName: { type: 'String' },
className: { type: 'String' },
triggerName: { type: 'String' },
url: { type: 'String' },
},
_GlobalConfig: {
objectId: { type: 'String' },
params: { type: 'Object' },
masterKeyOnly: { type: 'Object' },
},
_GraphQLConfig: {
objectId: { type: 'String' },
config: { type: 'Object' },
},
_Audience: {
objectId: { type: 'String' },
name: { type: 'String' },
query: { type: 'String' }, //storing query as JSON string to prevent "Nested keys should not contain the '$' or '.' characters" error
lastUsed: { type: 'Date' },
timesUsed: { type: 'Number' },
},
_Idempotency: {
reqId: { type: 'String' },
expire: { type: 'Date' },
},
});
const requiredColumns = Object.freeze({
_Product: ['productIdentifier', 'icon', 'order', 'title', 'subtitle'],
_Role: ['name', 'ACL'],
});
const invalidColumns = ['length'];
const systemClasses = Object.freeze([
'_User',
'_Installation',
'_Role',
'_Session',
'_Product',
'_PushStatus',
'_JobStatus',
'_JobSchedule',
'_Audience',
'_Idempotency',
]);
const volatileClasses = Object.freeze([
'_JobStatus',
'_PushStatus',
'_Hooks',
'_GlobalConfig',
'_GraphQLConfig',
'_JobSchedule',
'_Audience',
'_Idempotency',
]);
// Anything that start with role
const roleRegex = /^role:.*/;
// Anything that starts with userField (allowed for protected fields only)
const protectedFieldsPointerRegex = /^userField:.*/;
// * permission
const publicRegex = /^\*$/;
const authenticatedRegex = /^authenticated$/;
const requiresAuthenticationRegex = /^requiresAuthentication$/;
const clpPointerRegex = /^pointerFields$/;
// regex for validating entities in protectedFields object
const protectedFieldsRegex = Object.freeze([
protectedFieldsPointerRegex,
publicRegex,
authenticatedRegex,
roleRegex,
]);
// clp regex
const clpFieldsRegex = Object.freeze([
clpPointerRegex,
publicRegex,
requiresAuthenticationRegex,
roleRegex,
]);
function validatePermissionKey(key, userIdRegExp) {
let matchesSome = false;
for (const regEx of clpFieldsRegex) {
if (key.match(regEx) !== null) {
matchesSome = true;
break;
}
}
// userId depends on startup options so it's dynamic
const valid = matchesSome || key.match(userIdRegExp) !== null;
if (!valid) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`'${key}' is not a valid key for class level permissions`
);
}
}
function validateProtectedFieldsKey(key, userIdRegExp) {
let matchesSome = false;
for (const regEx of protectedFieldsRegex) {
if (key.match(regEx) !== null) {
matchesSome = true;
break;
}
}
// userId regex depends on launch options so it's dynamic
const valid = matchesSome || key.match(userIdRegExp) !== null;
if (!valid) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`'${key}' is not a valid key for class level permissions`
);
}
}
const CLPValidKeys = Object.freeze([
'find',
'count',
'get',
'create',
'update',
'delete',
'addField',
'readUserFields',
'writeUserFields',
'protectedFields',
]);
// validation before setting class-level permissions on collection
function validateCLP(perms: ClassLevelPermissions, fields: SchemaFields, userIdRegExp: RegExp) {
if (!perms) {
return;
}
for (const operationKey in perms) {
if (CLPValidKeys.indexOf(operationKey) == -1) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`${operationKey} is not a valid operation for class level permissions`
);
}
const operation = perms[operationKey];
// proceed with next operationKey
// throws when root fields are of wrong type
validateCLPjson(operation, operationKey);
if (operationKey === 'readUserFields' || operationKey === 'writeUserFields') {
// validate grouped pointer permissions
// must be an array with field names
for (const fieldName of operation) {
validatePointerPermission(fieldName, fields, operationKey);
}
// readUserFields and writerUserFields do not have nesdted fields
// proceed with next operationKey
continue;
}
// validate protected fields
if (operationKey === 'protectedFields') {
for (const entity in operation) {
// throws on unexpected key
validateProtectedFieldsKey(entity, userIdRegExp);
const protectedFields = operation[entity];
if (!Array.isArray(protectedFields)) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`'${protectedFields}' is not a valid value for protectedFields[${entity}] - expected an array.`
);
}
// if the field is in form of array
for (const field of protectedFields) {
// do not alloow to protect default fields
if (defaultColumns._Default[field]) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`Default field '${field}' can not be protected`
);
}
// field should exist on collection
if (!Object.prototype.hasOwnProperty.call(fields, field)) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`Field '${field}' in protectedFields:${entity} does not exist`
);
}
}
}
// proceed with next operationKey
continue;
}
// validate other fields
// Entity can be:
// "*" - Public,
// "requiresAuthentication" - authenticated users,
// "objectId" - _User id,
// "role:rolename",
// "pointerFields" - array of field names containing pointers to users
for (const entity in operation) {
// throws on unexpected key
validatePermissionKey(entity, userIdRegExp);
// entity can be either:
// "pointerFields": string[]
if (entity === 'pointerFields') {
const pointerFields = operation[entity];
if (Array.isArray(pointerFields)) {
for (const pointerField of pointerFields) {
validatePointerPermission(pointerField, fields, operation);
}
} else {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`'${pointerFields}' is not a valid value for ${operationKey}[${entity}] - expected an array.`
);
}
// proceed with next entity key
continue;
}
// or [entity]: boolean
const permit = operation[entity];
if (permit !== true) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`'${permit}' is not a valid value for class level permissions ${operationKey}:${entity}:${permit}`
);
}
}
}
}
function validateCLPjson(operation: any, operationKey: string) {
if (operationKey === 'readUserFields' || operationKey === 'writeUserFields') {
if (!Array.isArray(operation)) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`'${operation}' is not a valid value for class level permissions ${operationKey} - must be an array`
);
}
} else {
if (typeof operation === 'object' && operation !== null) {
// ok to proceed
return;
} else {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`'${operation}' is not a valid value for class level permissions ${operationKey} - must be an object`
);
}
}
}
function validatePointerPermission(fieldName: string, fields: Object, operation: string) {
// Uses collection schema to ensure the field is of type:
// - Pointer<_User> (pointers)
// - Array
//
// It's not possible to enforce type on Array's items in schema
// so we accept any Array field, and later when applying permissions
// only items that are pointers to _User are considered.
if (
!(
fields[fieldName] &&
((fields[fieldName].type == 'Pointer' && fields[fieldName].targetClass == '_User') ||
fields[fieldName].type == 'Array')
)
) {
throw new Parse.Error(
Parse.Error.INVALID_JSON,
`'${fieldName}' is not a valid column for class level pointer permissions ${operation}`
);
}
}
const joinClassRegex = /^_Join:[A-Za-z0-9_]+:[A-Za-z0-9_]+/;
const classAndFieldRegex = /^[A-Za-z][A-Za-z0-9_]*$/;
function classNameIsValid(className: string): boolean {
// Valid classes must:
return (
// Be one of _User, _Installation, _Role, _Session OR
systemClasses.indexOf(className) > -1 ||
// Be a join table OR
joinClassRegex.test(className) ||
// Include only alpha-numeric and underscores, and not start with an underscore or number
fieldNameIsValid(className, className)
);
}
// Valid fields must be alpha-numeric, and not start with an underscore or number
// must not be a reserved key
function fieldNameIsValid(fieldName: string, className: string): boolean {
if (className && className !== '_Hooks') {
if (fieldName === 'className') {
return false;
}
}
return classAndFieldRegex.test(fieldName) && !invalidColumns.includes(fieldName);
}
// Checks that it's not trying to clobber one of the default fields of the class.
function fieldNameIsValidForClass(fieldName: string, className: string): boolean {
if (!fieldNameIsValid(fieldName, className)) {
return false;
}
if (defaultColumns._Default[fieldName]) {
return false;
}
if (defaultColumns[className] && defaultColumns[className][fieldName]) {
return false;
}
return true;
}
function invalidClassNameMessage(className: string): string {
return (
'Invalid classname: ' +
className +
', classnames can only have alphanumeric characters and _, and must start with an alpha character '
);
}
const invalidJsonError = new Parse.Error(Parse.Error.INVALID_JSON, 'invalid JSON');
const validNonRelationOrPointerTypes = [
'Number',
'String',
'Boolean',
'Date',
'Object',
'Array',
'GeoPoint',
'File',
'Bytes',
'Polygon',
];
// Returns an error suitable for throwing if the type is invalid
const fieldTypeIsInvalid = ({ type, targetClass }) => {
if (['Pointer', 'Relation'].indexOf(type) >= 0) {
if (!targetClass) {
return new Parse.Error(135, `type ${type} needs a class name`);
} else if (typeof targetClass !== 'string') {
return invalidJsonError;
} else if (!classNameIsValid(targetClass)) {
return new Parse.Error(Parse.Error.INVALID_CLASS_NAME, invalidClassNameMessage(targetClass));
} else {
return undefined;
}
}
if (typeof type !== 'string') {
return invalidJsonError;
}
if (validNonRelationOrPointerTypes.indexOf(type) < 0) {
return new Parse.Error(Parse.Error.INCORRECT_TYPE, `invalid field type: ${type}`);
}
return undefined;
};
const convertSchemaToAdapterSchema = (schema: any) => {
schema = injectDefaultSchema(schema);
delete schema.fields.ACL;
schema.fields._rperm = { type: 'Array' };
schema.fields._wperm = { type: 'Array' };
if (schema.className === '_User') {
delete schema.fields.password;
schema.fields._hashed_password = { type: 'String' };
}
return schema;
};
const convertAdapterSchemaToParseSchema = ({ ...schema }) => {
delete schema.fields._rperm;
delete schema.fields._wperm;
schema.fields.ACL = { type: 'ACL' };
if (schema.className === '_User') {
delete schema.fields.authData; //Auth data is implicit
delete schema.fields._hashed_password;
schema.fields.password = { type: 'String' };
}
if (schema.indexes && Object.keys(schema.indexes).length === 0) {
delete schema.indexes;
}
return schema;
};
class SchemaData {
__data: any;
__protectedFields: any;
constructor(allSchemas = [], protectedFields = {}) {
this.__data = {};
this.__protectedFields = protectedFields;
allSchemas.forEach(schema => {
if (volatileClasses.includes(schema.className)) {
return;
}
Object.defineProperty(this, schema.className, {
get: () => {
if (!this.__data[schema.className]) {
const data = {};
data.fields = injectDefaultSchema(schema).fields;
data.classLevelPermissions = deepcopy(schema.classLevelPermissions);
data.indexes = schema.indexes;
const classProtectedFields = this.__protectedFields[schema.className];
if (classProtectedFields) {
for (const key in classProtectedFields) {
const unq = new Set([
...(data.classLevelPermissions.protectedFields[key] || []),
...classProtectedFields[key],
]);
data.classLevelPermissions.protectedFields[key] = Array.from(unq);
}
}
this.__data[schema.className] = data;
}
return this.__data[schema.className];
},
});
});
// Inject the in-memory classes
volatileClasses.forEach(className => {
Object.defineProperty(this, className, {
get: () => {
if (!this.__data[className]) {
const schema = injectDefaultSchema({
className,
fields: {},
classLevelPermissions: {},
});
const data = {};
data.fields = schema.fields;
data.classLevelPermissions = schema.classLevelPermissions;
data.indexes = schema.indexes;
this.__data[className] = data;
}
return this.__data[className];
},
});
});
}
}
const injectDefaultSchema = ({ className, fields, classLevelPermissions, indexes }: Schema) => {
const defaultSchema: Schema = {
className,
fields: {
...defaultColumns._Default,
...(defaultColumns[className] || {}),
...fields,
},
classLevelPermissions,
};
if (indexes && Object.keys(indexes).length !== 0) {
defaultSchema.indexes = indexes;
}
return defaultSchema;
};
const _HooksSchema = { className: '_Hooks', fields: defaultColumns._Hooks };
const _GlobalConfigSchema = {
className: '_GlobalConfig',
fields: defaultColumns._GlobalConfig,
};
const _GraphQLConfigSchema = {
className: '_GraphQLConfig',
fields: defaultColumns._GraphQLConfig,
};
const _PushStatusSchema = convertSchemaToAdapterSchema(
injectDefaultSchema({
className: '_PushStatus',
fields: {},
classLevelPermissions: {},
})
);
const _JobStatusSchema = convertSchemaToAdapterSchema(
injectDefaultSchema({
className: '_JobStatus',
fields: {},
classLevelPermissions: {},
})
);
const _JobScheduleSchema = convertSchemaToAdapterSchema(
injectDefaultSchema({
className: '_JobSchedule',
fields: {},
classLevelPermissions: {},
})
);
const _AudienceSchema = convertSchemaToAdapterSchema(
injectDefaultSchema({
className: '_Audience',
fields: defaultColumns._Audience,
classLevelPermissions: {},
})
);
const _IdempotencySchema = convertSchemaToAdapterSchema(
injectDefaultSchema({
className: '_Idempotency',
fields: defaultColumns._Idempotency,
classLevelPermissions: {},
})
);
const VolatileClassesSchemas = [
_HooksSchema,
_JobStatusSchema,
_JobScheduleSchema,
_PushStatusSchema,
_GlobalConfigSchema,
_GraphQLConfigSchema,
_AudienceSchema,
_IdempotencySchema,
];
const dbTypeMatchesObjectType = (dbType: SchemaField | string, objectType: SchemaField) => {
if (dbType.type !== objectType.type) return false;
if (dbType.targetClass !== objectType.targetClass) return false;
if (dbType === objectType.type) return true;
if (dbType.type === objectType.type) return true;
return false;
};
const typeToString = (type: SchemaField | string): string => {
if (typeof type === 'string') {
return type;
}
if (type.targetClass) {
return `${type.type}<${type.targetClass}>`;
}
return `${type.type}`;
};
// Stores the entire schema of the app in a weird hybrid format somewhere between
// the mongo format and the Parse format. Soon, this will all be Parse format.
export default class SchemaController {
_dbAdapter: StorageAdapter;
schemaData: { [string]: Schema };
reloadDataPromise: ?Promise<any>;
protectedFields: any;
userIdRegEx: RegExp;
constructor(databaseAdapter: StorageAdapter) {
this._dbAdapter = databaseAdapter;
this.schemaData = new SchemaData(SchemaCache.all(), this.protectedFields);
this.protectedFields = Config.get(Parse.applicationId).protectedFields;
const customIds = Config.get(Parse.applicationId).allowCustomObjectId;
const customIdRegEx = /^.{1,}$/u; // 1+ chars
const autoIdRegEx = /^[a-zA-Z0-9]{1,}$/;
this.userIdRegEx = customIds ? customIdRegEx : autoIdRegEx;
this._dbAdapter.watch(() => {
this.reloadData({ clearCache: true });
});
}
reloadData(options: LoadSchemaOptions = { clearCache: false }): Promise<any> {
if (this.reloadDataPromise && !options.clearCache) {
return this.reloadDataPromise;
}
this.reloadDataPromise = this.getAllClasses(options)
.then(
allSchemas => {
this.schemaData = new SchemaData(allSchemas, this.protectedFields);
delete this.reloadDataPromise;
},
err => {
this.schemaData = new SchemaData();
delete this.reloadDataPromise;
throw err;
}
)
.then(() => {});
return this.reloadDataPromise;
}
getAllClasses(options: LoadSchemaOptions = { clearCache: false }): Promise<Array<Schema>> {
if (options.clearCache) {
return this.setAllClasses();
}
const cached = SchemaCache.all();
if (cached && cached.length) {
return Promise.resolve(cached);
}
return this.setAllClasses();
}
setAllClasses(): Promise<Array<Schema>> {
return this._dbAdapter
.getAllClasses()
.then(allSchemas => allSchemas.map(injectDefaultSchema))
.then(allSchemas => {
SchemaCache.put(allSchemas);
return allSchemas;
});
}
getOneSchema(
className: string,
allowVolatileClasses: boolean = false,
options: LoadSchemaOptions = { clearCache: false }
): Promise<Schema> {
if (options.clearCache) {
SchemaCache.clear();
}
if (allowVolatileClasses && volatileClasses.indexOf(className) > -1) {
const data = this.schemaData[className];
return Promise.resolve({
className,
fields: data.fields,
classLevelPermissions: data.classLevelPermissions,
indexes: data.indexes,
});
}
const cached = SchemaCache.get(className);
if (cached && !options.clearCache) {
return Promise.resolve(cached);
}
return this.setAllClasses().then(allSchemas => {
const oneSchema = allSchemas.find(schema => schema.className === className);
if (!oneSchema) {
return Promise.reject(undefined);
}
return oneSchema;
});
}
// Create a new class that includes the three default fields.
// ACL is an implicit column that does not get an entry in the
// _SCHEMAS database. Returns a promise that resolves with the
// created schema, in mongo format.
// on success, and rejects with an error on fail. Ensure you
// have authorization (master key, or client class creation
// enabled) before calling this function.
async addClassIfNotExists(
className: string,
fields: SchemaFields = {},
classLevelPermissions: any,
indexes: any = {}
): Promise<void | Schema> {
var validationError = this.validateNewClass(className, fields, classLevelPermissions);
if (validationError) {
if (validationError instanceof Parse.Error) {
return Promise.reject(validationError);
} else if (validationError.code && validationError.error) {
return Promise.reject(new Parse.Error(validationError.code, validationError.error));
}
return Promise.reject(validationError);
}
try {
const adapterSchema = await this._dbAdapter.createClass(
className,
convertSchemaToAdapterSchema({
fields,
classLevelPermissions,
indexes,
className,
})
);
// TODO: Remove by updating schema cache directly
await this.reloadData({ clearCache: true });
const parseSchema = convertAdapterSchemaToParseSchema(adapterSchema);
return parseSchema;
} catch (error) {
if (error && error.code === Parse.Error.DUPLICATE_VALUE) {
throw new Parse.Error(Parse.Error.INVALID_CLASS_NAME, `Class ${className} already exists.`);
} else {
throw error;
}
}
}
updateClass(
className: string,
submittedFields: SchemaFields,
classLevelPermissions: any,
indexes: any,
database: DatabaseController
) {
return this.getOneSchema(className)
.then(schema => {
const existingFields = schema.fields;
Object.keys(submittedFields).forEach(name => {
const field = submittedFields[name];
if (
existingFields[name] &&
existingFields[name].type !== field.type &&
field.__op !== 'Delete'
) {
throw new Parse.Error(255, `Field ${name} exists, cannot update.`);
}
if (!existingFields[name] && field.__op === 'Delete') {
throw new Parse.Error(255, `Field ${name} does not exist, cannot delete.`);
}
});
delete existingFields._rperm;
delete existingFields._wperm;
const newSchema = buildMergedSchemaObject(existingFields, submittedFields);
const defaultFields = defaultColumns[className] || defaultColumns._Default;
const fullNewSchema = Object.assign({}, newSchema, defaultFields);
const validationError = this.validateSchemaData(
className,
newSchema,
classLevelPermissions,
Object.keys(existingFields)
);
if (validationError) {
throw new Parse.Error(validationError.code, validationError.error);
}
// Finally we have checked to make sure the request is valid and we can start deleting fields.
// Do all deletions first, then a single save to _SCHEMA collection to handle all additions.
const deletedFields: string[] = [];
const insertedFields = [];
Object.keys(submittedFields).forEach(fieldName => {
if (submittedFields[fieldName].__op === 'Delete') {
deletedFields.push(fieldName);
} else {
insertedFields.push(fieldName);
}
});
let deletePromise = Promise.resolve();
if (deletedFields.length > 0) {
deletePromise = this.deleteFields(deletedFields, className, database);
}
let enforceFields = [];
return (
deletePromise // Delete Everything
.then(() => this.reloadData({ clearCache: true })) // Reload our Schema, so we have all the new values
.then(() => {
const promises = insertedFields.map(fieldName => {
const type = submittedFields[fieldName];
return this.enforceFieldExists(className, fieldName, type);
});
return Promise.all(promises);
})
.then(results => {
enforceFields = results.filter(result => !!result);
return this.setPermissions(className, classLevelPermissions, newSchema);
})
.then(() =>
this._dbAdapter.setIndexesWithSchemaFormat(
className,
indexes,
schema.indexes,
fullNewSchema
)
)
.then(() => this.reloadData({ clearCache: true }))
//TODO: Move this logic into the database adapter
.then(() => {
this.ensureFields(enforceFields);
const schema = this.schemaData[className];
const reloadedSchema: Schema = {
className: className,
fields: schema.fields,
classLevelPermissions: schema.classLevelPermissions,
};
if (schema.indexes && Object.keys(schema.indexes).length !== 0) {
reloadedSchema.indexes = schema.indexes;
}
return reloadedSchema;
})
);
})
.catch(error => {
if (error === undefined) {
throw new Parse.Error(
Parse.Error.INVALID_CLASS_NAME,
`Class ${className} does not exist.`
);
} else {
throw error;
}
});
}
// Returns a promise that resolves successfully to the new schema
// object or fails with a reason.
enforceClassExists(className: string): Promise<SchemaController> {
if (this.schemaData[className]) {
return Promise.resolve(this);
}
// We don't have this class. Update the schema
return (
// The schema update succeeded. Reload the schema
this.addClassIfNotExists(className)
.catch(() => {
// The schema update failed. This can be okay - it might
// have failed because there's a race condition and a different
// client is making the exact same schema update that we want.
// So just reload the schema.
return this.reloadData({ clearCache: true });
})
.then(() => {
// Ensure that the schema now validates
if (this.schemaData[className]) {
return this;
} else {
throw new Parse.Error(Parse.Error.INVALID_JSON, `Failed to add ${className}`);
}
})
.catch(() => {
// The schema still doesn't validate. Give up
throw new Parse.Error(Parse.Error.INVALID_JSON, 'schema class name does not revalidate');
})
);
}
validateNewClass(className: string, fields: SchemaFields = {}, classLevelPermissions: any): any {
if (this.schemaData[className]) {
throw new Parse.Error(Parse.Error.INVALID_CLASS_NAME, `Class ${className} already exists.`);
}
if (!classNameIsValid(className)) {
return {
code: Parse.Error.INVALID_CLASS_NAME,
error: invalidClassNameMessage(className),
};
}
return this.validateSchemaData(className, fields, classLevelPermissions, []);
}
validateSchemaData(
className: string,
fields: SchemaFields,
classLevelPermissions: ClassLevelPermissions,
existingFieldNames: Array<string>
) {
for (const fieldName in fields) {
if (existingFieldNames.indexOf(fieldName) < 0) {
if (!fieldNameIsValid(fieldName, className)) {
return {
code: Parse.Error.INVALID_KEY_NAME,
error: 'invalid field name: ' + fieldName,
};
}
if (!fieldNameIsValidForClass(fieldName, className)) {
return {
code: 136,
error: 'field ' + fieldName + ' cannot be added',
};
}
const fieldType = fields[fieldName];
const error = fieldTypeIsInvalid(fieldType);
if (error) return { code: error.code, error: error.message };
if (fieldType.defaultValue !== undefined) {
let defaultValueType = getType(fieldType.defaultValue);
if (typeof defaultValueType === 'string') {
defaultValueType = { type: defaultValueType };