-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathcheck-schema.ts
553 lines (504 loc) · 18.2 KB
/
check-schema.ts
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
/**
* does additional checks over the schema-json
* to ensure nothing is broken or not supported
*/
import {
newRxError
} from '../../rx-error.ts';
import { getPrimaryFieldOfPrimaryKey, getSchemaByObjectPath } from '../../rx-schema-helper.ts';
import type {
CompositePrimaryKey,
JsonSchema,
JsonSchemaTypes,
RxJsonSchema,
TopLevelProperty
} from '../../types/index.d.ts';
import {
appendToArray,
flattenObject, getProperty, isMaybeReadonlyArray,
trimDots
} from '../../plugins/utils/index.ts';
import { rxDocumentProperties } from './entity-properties.ts';
/**
* checks if the fieldname is allowed
* this makes sure that the fieldnames can be transformed into javascript-vars
* and does not conquer the observe$ and populate_ fields
* @throws {Error}
*/
export function checkFieldNameRegex(fieldName: string) {
if (fieldName === '_deleted') {
return;
}
if (['properties'].includes(fieldName)) {
throw newRxError('SC23', {
fieldName
});
}
const regexStr = '^[a-zA-Z](?:[[a-zA-Z0-9_]*]?[a-zA-Z0-9])?$';
const regex = new RegExp(regexStr);
if (
/**
* It must be allowed to set _id as primaryKey.
* This makes it sometimes easier to work with RxDB+CouchDB
* @link https://github.com/pubkey/rxdb/issues/681
*/
fieldName !== '_id' &&
!fieldName.match(regex)
) {
throw newRxError('SC1', {
regex: regexStr,
fieldName
});
}
}
/**
* validate that all schema-related things are ok
*/
export function validateFieldsDeep(rxJsonSchema: RxJsonSchema<any>): true {
const primaryPath = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);
function checkField(
fieldName: string,
schemaObj: JsonSchema<any>,
path: string
) {
if (
typeof fieldName === 'string' &&
typeof schemaObj === 'object' &&
!Array.isArray(schemaObj) &&
path.split('.').pop() !== 'patternProperties'
) checkFieldNameRegex(fieldName);
// 'item' only allowed it type=='array'
if (Object.prototype.hasOwnProperty.call(schemaObj, 'item') && schemaObj.type !== 'array') {
throw newRxError('SC2', {
fieldName
});
}
/**
* required fields cannot be set via 'required: true',
* but must be set via required: []
*/
if (
Object.prototype.hasOwnProperty.call(schemaObj, 'required') &&
typeof schemaObj.required === 'boolean'
) {
throw newRxError('SC24', {
fieldName
});
}
// $ref is not allowed
if (Object.prototype.hasOwnProperty.call(schemaObj, '$ref')) {
throw newRxError('SC40', {
fieldName
});
}
// if ref given, must be type=='string', type=='array' with string-items or type==['string','null']
if (Object.prototype.hasOwnProperty.call(schemaObj, 'ref')) {
if (Array.isArray(schemaObj.type)) {
if (schemaObj.type.length > 2 || !schemaObj.type.includes('string') || !schemaObj.type.includes('null')) {
throw newRxError('SC4', {
fieldName
});
}
} else {
switch (schemaObj.type) {
case 'string':
break;
case 'array':
if (
!schemaObj.items ||
!(schemaObj.items as any).type ||
(schemaObj.items as any).type !== 'string'
) {
throw newRxError('SC3', {
fieldName
});
}
break;
default:
throw newRxError('SC4', {
fieldName
});
}
}
}
const isNested = path.split('.').length >= 2;
// nested only
if (isNested) {
if ((schemaObj as any).default) {
throw newRxError('SC7', {
path
});
}
}
// first level
if (!isNested) {
// if _id is used, it must be primaryKey
if (
fieldName === '_id' &&
primaryPath !== '_id'
) {
throw newRxError('COL2', {
fieldName
});
}
// check underscore fields
if (fieldName.charAt(0) === '_') {
if (
// exceptional allow underscore on these fields.
fieldName === '_id' ||
fieldName === '_deleted'
) {
return;
}
throw newRxError('SC8', {
fieldName
});
}
}
}
function traverse(currentObj: any, currentPath: any) {
if (!currentObj || typeof currentObj !== 'object') {
return;
}
Object.keys(currentObj).forEach(attributeName => {
const schemaObj = currentObj[attributeName];
if (
!currentObj.properties &&
schemaObj &&
typeof schemaObj === 'object' &&
!Array.isArray(currentObj)
) {
checkField(
attributeName,
schemaObj,
currentPath
);
}
let nextPath = currentPath;
if (attributeName !== 'properties') nextPath = nextPath + '.' + attributeName;
traverse(schemaObj, nextPath);
});
}
traverse(rxJsonSchema, '');
return true;
}
export function checkPrimaryKey(
jsonSchema: RxJsonSchema<any>
) {
if (!jsonSchema.primaryKey) {
throw newRxError('SC30', { schema: jsonSchema });
}
function validatePrimarySchemaPart(
schemaPart: JsonSchema | TopLevelProperty
) {
if (!schemaPart) {
throw newRxError('SC33', { schema: jsonSchema });
}
const type: string = schemaPart.type as any;
if (
!type ||
!['string', 'number', 'integer'].includes(type)
) {
throw newRxError('SC32', { schema: jsonSchema, args: { schemaPart } });
}
}
if (typeof jsonSchema.primaryKey === 'string') {
const key = jsonSchema.primaryKey;
const schemaPart = jsonSchema.properties[key];
validatePrimarySchemaPart(schemaPart);
} else {
const compositePrimaryKey: CompositePrimaryKey<any> = jsonSchema.primaryKey as any;
const keySchemaPart = getSchemaByObjectPath(jsonSchema, compositePrimaryKey.key);
validatePrimarySchemaPart(keySchemaPart);
compositePrimaryKey.fields.forEach(field => {
const schemaPart = getSchemaByObjectPath(jsonSchema, field);
validatePrimarySchemaPart(schemaPart);
});
}
/**
* The primary key must have a maxLength set
* which is required by some RxStorage implementations
* to ensure we can craft custom index strings.
*/
const primaryPath = getPrimaryFieldOfPrimaryKey(jsonSchema.primaryKey);
const primaryPathSchemaPart = jsonSchema.properties[primaryPath];
if (!primaryPathSchemaPart.maxLength) {
throw newRxError('SC39', { schema: jsonSchema, args: { primaryPathSchemaPart } });
} else if (!isFinite(primaryPathSchemaPart.maxLength)) {
throw newRxError('SC41', { schema: jsonSchema, args: { primaryPathSchemaPart } });
}
}
/**
* computes real path of the object path in the collection schema
*/
function getSchemaPropertyRealPath(shortPath: string) {
const pathParts = shortPath.split('.');
let realPath = '';
for (let i = 0; i < pathParts.length; i += 1) {
if (pathParts[i] !== '[]') {
realPath = realPath.concat('.properties.'.concat(pathParts[i]));
} else {
realPath = realPath.concat('.items');
}
}
return trimDots(realPath);
}
/**
* does the checking
* @throws {Error} if something is not ok
*/
export function checkSchema(jsonSchema: RxJsonSchema<any>) {
if (!jsonSchema.primaryKey) {
throw newRxError('SC30', {
schema: jsonSchema
});
}
if (!Object.prototype.hasOwnProperty.call(jsonSchema, 'properties')) {
throw newRxError('SC29', {
schema: jsonSchema
});
}
// _rev MUST NOT exist, it is added by RxDB
if (jsonSchema.properties._rev) {
throw newRxError('SC10', {
schema: jsonSchema
});
}
// check version
if (!Object.prototype.hasOwnProperty.call(jsonSchema, 'version') ||
typeof jsonSchema.version !== 'number' ||
jsonSchema.version < 0
) {
throw newRxError('SC11', {
version: jsonSchema.version
});
}
validateFieldsDeep(jsonSchema);
checkPrimaryKey(jsonSchema);
Object.keys(jsonSchema.properties).forEach(key => {
const value: any = jsonSchema.properties[key];
// check primary
if (key === jsonSchema.primaryKey) {
if (jsonSchema.indexes && jsonSchema.indexes.includes(key)) {
throw newRxError('SC13', {
value,
schema: jsonSchema
});
}
if (value.unique) {
throw newRxError('SC14', {
value,
schema: jsonSchema
});
}
if (jsonSchema.encrypted && jsonSchema.encrypted.includes(key)) {
throw newRxError('SC15', {
value,
schema: jsonSchema
});
}
if (value.type !== 'string') {
throw newRxError('SC16', {
value,
schema: jsonSchema
});
}
}
// check if RxDocument-property
if (rxDocumentProperties().includes(key)) {
throw newRxError('SC17', {
key,
schema: jsonSchema
});
}
});
// check format of jsonSchema.indexes
if (jsonSchema.indexes) {
// should be an array
if (!isMaybeReadonlyArray(jsonSchema.indexes)) {
throw newRxError('SC18', {
indexes: jsonSchema.indexes,
schema: jsonSchema
});
}
jsonSchema.indexes.forEach(index => {
// should contain strings or array of strings
if (!(typeof index === 'string' || Array.isArray(index))) {
throw newRxError('SC19', { index, schema: jsonSchema });
}
// if is a compound index it must contain strings
if (Array.isArray(index)) {
for (let i = 0; i < index.length; i += 1) {
if (typeof index[i] !== 'string') {
throw newRxError('SC20', { index, schema: jsonSchema });
}
}
}
/**
* To be able to craft custom indexable string with compound fields,
* we need to know the maximum fieldlength of the fields values
* when they are transformed to strings.
* Therefore we need to enforce some properties inside of the schema.
*/
const indexAsArray = isMaybeReadonlyArray(index) ? index : [index];
indexAsArray.forEach(fieldName => {
const schemaPart = getSchemaByObjectPath(
jsonSchema,
fieldName
);
const type: JsonSchemaTypes = schemaPart.type as any;
switch (type) {
case 'string':
const maxLength = schemaPart.maxLength;
if (!maxLength) {
throw newRxError('SC34', {
index,
field: fieldName,
schema: jsonSchema
});
}
break;
case 'number':
case 'integer':
const multipleOf = schemaPart.multipleOf;
if (!multipleOf) {
throw newRxError('SC35', {
index,
field: fieldName,
schema: jsonSchema
});
}
const maximum = schemaPart.maximum;
const minimum = schemaPart.minimum;
if (
typeof maximum === 'undefined' ||
typeof minimum === 'undefined'
) {
throw newRxError('SC37', {
index,
field: fieldName,
schema: jsonSchema
});
}
if (
!isFinite(maximum) ||
!isFinite(minimum)
) {
throw newRxError('SC41', {
index,
field: fieldName,
schema: jsonSchema
});
}
break;
case 'boolean':
/**
* If a boolean field is used as an index,
* it must be required.
*/
let parentPath = '';
let lastPathPart = fieldName;
if (fieldName.includes('.')) {
const partParts = fieldName.split('.');
lastPathPart = partParts.pop();
parentPath = partParts.join('.');
}
const parentSchemaPart = parentPath === '' ? jsonSchema : getSchemaByObjectPath(
jsonSchema,
parentPath
);
if (
!parentSchemaPart.required ||
!parentSchemaPart.required.includes(lastPathPart)
) {
throw newRxError('SC38', {
index,
field: fieldName,
schema: jsonSchema
});
}
break;
default:
throw newRxError('SC36', {
fieldName,
type: schemaPart.type as any,
schema: jsonSchema,
});
}
});
});
}
// remove backward-compatibility for index: true
Object.keys(flattenObject(jsonSchema))
.map(key => {
// flattenObject returns only ending paths, we need all paths pointing to an object
const split = key.split('.');
split.pop(); // all but last
return split.join('.');
})
.filter(key => key !== '')
.filter((elem, pos, arr) => arr.indexOf(elem) === pos) // unique
.filter(key => { // check if this path defines an index
const value = getProperty(jsonSchema, key);
return value && !!value.index;
})
.forEach(key => { // replace inner properties
key = key.replace('properties.', ''); // first
key = key.replace(/\.properties\./g, '.'); // middle
throw newRxError('SC26', {
index: trimDots(key),
schema: jsonSchema
});
});
/* check types of the indexes */
(jsonSchema.indexes || [])
.reduce((indexPaths: string[], currentIndex) => {
if (isMaybeReadonlyArray(currentIndex)) {
appendToArray(indexPaths, currentIndex);
} else {
indexPaths.push(currentIndex);
}
return indexPaths;
}, [])
.filter((elem, pos, arr) => arr.indexOf(elem) === pos) // from now on working only with unique indexes
.map(indexPath => {
const realPath = getSchemaPropertyRealPath(indexPath); // real path in the collection schema
const schemaObj = getProperty(jsonSchema, realPath); // get the schema of the indexed property
if (!schemaObj || typeof schemaObj !== 'object') {
throw newRxError('SC21', {
index: indexPath,
schema: jsonSchema
});
}
return { indexPath, schemaObj };
})
.filter(index =>
index.schemaObj.type !== 'string' &&
index.schemaObj.type !== 'integer' &&
index.schemaObj.type !== 'number' &&
index.schemaObj.type !== 'boolean'
)
.forEach(index => {
throw newRxError('SC22', {
key: index.indexPath,
type: index.schemaObj.type,
schema: jsonSchema
});
});
/* ensure encrypted fields exist in the schema */
if (jsonSchema.encrypted) {
jsonSchema.encrypted
.forEach(propPath => {
// real path in the collection schema
const realPath = getSchemaPropertyRealPath(propPath);
// get the schema of the indexed property
const schemaObj = getProperty(jsonSchema, realPath);
if (!schemaObj || typeof schemaObj !== 'object') {
throw newRxError('SC28', {
field: propPath,
schema: jsonSchema
});
}
});
}
}