-
-
Notifications
You must be signed in to change notification settings - Fork 113
/
SimpleSchema.ts
1349 lines (1180 loc) · 44.7 KB
/
SimpleSchema.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
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
/* eslint-disable no-undef */
import MongoObject from 'mongo-object'
import clean from './clean.js'
import { getDefaultErrorMessage } from './defaultMessages.js'
import { ClientError } from './errors.js'
import expandShorthand from './expandShorthand.js'
import SimpleSchemaGroup from './SimpleSchemaGroup.js'
import {
AutoValueContext,
AutoValueFunctionDetails,
CleanOptions,
DocValidatorFunction,
PartialSchemaDefinitionWithShorthand,
ResolvedSchemaDefinition,
SchemaDefinition,
SchemaDefinitionWithShorthand,
SchemaKeyDefinition,
SchemaKeyDefinitionWithOneType,
SimpleSchemaOptions,
StandardSchemaKeyDefinition,
StandardSchemaKeyDefinitionWithSimpleTypes,
SupportedTypes,
ValidationError,
ValidationOptions,
ValidatorFunction
} from './types.js'
import { forEachKeyAncestor, humanize, isEmptyObject } from './utility/index.js'
import ValidationContext from './ValidationContext.js'
export const schemaDefinitionOptions = [
'autoValue',
'defaultValue',
'label',
'optional',
'required',
'type'
]
const oneOfProps = [
'allowedValues',
'blackbox',
'custom',
'exclusiveMax',
'exclusiveMin',
'max',
'maxCount',
'min',
'minCount',
'regEx',
'skipRegExCheckForEmptyStrings',
'trim',
'type'
]
const propsThatCanBeFunction = [
'allowedValues',
'exclusiveMax',
'exclusiveMin',
'label',
'max',
'maxCount',
'min',
'minCount',
'optional',
'regEx',
'skipRegExCheckForEmptyStrings'
]
class SimpleSchema {
public static debug?: boolean
public static defaultLabel?: string
/**
* Packages that want to allow and check additional options
* should add the option names to this set.
*/
public static supportedConstructorOptions = new Set([
'clean',
'getErrorMessage',
'humanizeAutoLabels',
'keepRawDefinition',
'requiredByDefault'
])
/**
* Packages that want to allow and check additional options
* should add the option names to this set.
*/
public static supportedCleanOptions = new Set([
'autoConvert',
'extendAutoValueContext',
'filter',
'getAutoValues',
'isModifier',
'isUpsert',
'mongoObject',
'mutate',
'removeEmptyStrings',
'removeNullsFromArrays',
'trimStrings'
])
public static validationErrorTransform?: (error: ClientError<ValidationError[]>) => Error
public static version = 2
public version: number
// Global constructor options
private static _constructorOptionDefaults: SimpleSchemaOptions = {
clean: {
autoConvert: true,
extendAutoValueContext: {},
filter: true,
getAutoValues: true,
removeEmptyStrings: true,
removeNullsFromArrays: false,
trimStrings: true
},
humanizeAutoLabels: true,
requiredByDefault: true
}
private static readonly _docValidators: DocValidatorFunction[] = []
private static readonly _validators: ValidatorFunction[] = []
private _autoValues: AutoValueFunctionDetails[] = []
private _blackboxKeys = new Set<string>()
private _cleanOptions: CleanOptions = {}
private readonly _constructorOptions: SimpleSchemaOptions = {}
private _docValidators: DocValidatorFunction[] = []
private _firstLevelSchemaKeys: string[] = []
private readonly _rawDefinition: SchemaDefinitionWithShorthand | null = null
private _schema: ResolvedSchemaDefinition = {}
private _schemaKeys: string[] = []
// Named validation contexts
private _validationContexts: Record<string, ValidationContext> = {}
private _validators: ValidatorFunction[] = []
constructor (
schema: SchemaDefinitionWithShorthand = {},
options: SimpleSchemaOptions = {}
) {
// Stash the options object
this._constructorOptions = {
...SimpleSchema._constructorOptionDefaults,
...options
}
delete this._constructorOptions.clean // stored separately below
Object.getOwnPropertyNames(this._constructorOptions).forEach((opt) => {
if (!SimpleSchema.supportedConstructorOptions.has(opt)) {
console.warn(`Unsupported "${opt}" option passed to SimpleSchema constructor`)
}
})
// Schema-level defaults for cleaning
this._cleanOptions = {
...SimpleSchema._constructorOptionDefaults.clean,
...(options.clean ?? {})
}
// Custom validators for this instance
this._docValidators = []
// Clone, expanding shorthand, and store the schema object in this._schema
this.extend(schema)
// Clone raw definition and save if keepRawDefinition is active
if (this._constructorOptions.keepRawDefinition === true) {
this._rawDefinition = schema
}
this.version = SimpleSchema.version
}
/**
/* @returns The entire raw schema definition passed in the constructor
*/
get rawDefinition (): SchemaDefinitionWithShorthand | null {
return this._rawDefinition
}
forEachAncestorSimpleSchema (
key: string,
func: (
ssInstance: SimpleSchema,
ancestor: string,
ancestorGenericKey: string
) => void
): void {
const genericKey = MongoObject.makeKeyGeneric(key)
if (genericKey == null) return
forEachKeyAncestor(genericKey, (ancestor) => {
const def = this._schema[ancestor]
if (def == null) return
def.type.definitions.forEach((typeDef) => {
if (SimpleSchema.isSimpleSchema(typeDef.type)) {
func(typeDef.type as SimpleSchema, ancestor, genericKey.slice(ancestor.length + 1))
}
})
})
}
/**
* Returns whether the obj is a SimpleSchema object.
* @param [obj] An object to test
* @returns True if the given object appears to be a SimpleSchema instance
*/
static isSimpleSchema (obj: unknown): boolean {
if (obj == null) return false
return obj instanceof SimpleSchema || Object.prototype.hasOwnProperty.call(obj, '_schema')
}
/**
* @param key One specific or generic key for which to get the schema.
* @returns Returns a 2-tuple.
*
* First item: The SimpleSchema instance that actually defines the given key.
*
* For example, if you have several nested objects, each their own SimpleSchema
* instance, and you pass in 'outerObj.innerObj.innermostObj.name' as the key, you'll
* get back the SimpleSchema instance for `outerObj.innerObj.innermostObj` key.
*
* But if you pass in 'outerObj.innerObj.innermostObj.name' as the key and that key is
* defined in the main schema without use of subschemas, then you'll get back the main schema.
*
* Second item: The part of the key that is in the found schema.
*
* Always returns a tuple (array) but the values may be `null`.
*/
nearestSimpleSchemaInstance (
key: string | null
): [SimpleSchema | null, string | null] {
if (key == null) return [null, null]
const genericKey = MongoObject.makeKeyGeneric(key)
if (genericKey == null) return [null, null]
if (this._schema[genericKey] !== undefined) return [this, genericKey]
// If not defined in this schema, see if it's defined in a sub-schema
let innerKey
let nearestSimpleSchemaInstance: SimpleSchema | null = null
this.forEachAncestorSimpleSchema(
key,
(simpleSchema, ancestor, subSchemaKey) => {
if (
(nearestSimpleSchemaInstance == null) &&
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
simpleSchema._schema[subSchemaKey]
) {
nearestSimpleSchemaInstance = simpleSchema
innerKey = subSchemaKey
}
}
)
return innerKey != null ? [nearestSimpleSchemaInstance, innerKey] : [null, null]
}
/**
* @param [key] One specific or generic key for which to get the schema.
* @returns The entire schema object or just the definition for one key.
*
* Note that this returns the raw, unevaluated definition object. Use `getDefinition`
* if you want the evaluated definition, where any properties that are functions
* have been run to produce a result.
*/
schema (): ResolvedSchemaDefinition
schema (key: string): StandardSchemaKeyDefinition | null
schema (key?: string): ResolvedSchemaDefinition | StandardSchemaKeyDefinition | null {
if (key == null) return this._schema
const genericKey = MongoObject.makeKeyGeneric(key)
let keySchema = genericKey == null ? null : this._schema[genericKey]
// If not defined in this schema, see if it's defined in a subschema
if (keySchema == null) {
let found = false
this.forEachAncestorSimpleSchema(
key,
(simpleSchema, ancestor, subSchemaKey) => {
if (!found) keySchema = simpleSchema.schema(subSchemaKey)
if (keySchema != null) found = true
}
)
}
return keySchema
}
/**
* @param key One specific or generic key for which to get all possible schemas.
* @returns An potentially empty array of possible definitions for one key
*
* Note that this returns the raw, unevaluated definition object. Use `getDefinition`
* if you want the evaluated definition, where any properties that are functions
* have been run to produce a result.
*/
schemas (key: string): StandardSchemaKeyDefinition[] {
const schemas: StandardSchemaKeyDefinition[] = []
const genericKey = MongoObject.makeKeyGeneric(key)
const keySchema = genericKey == null ? null : this._schema[genericKey]
if (keySchema != null) schemas.push(keySchema)
// See if it's defined in any subschema
this.forEachAncestorSimpleSchema(
key,
(simpleSchema, ancestor, subSchemaKey) => {
const keyDef = simpleSchema.schema(subSchemaKey)
if (keyDef != null) schemas.push(keyDef)
}
)
return schemas
}
/**
* @returns {Object} The entire schema object with subschemas merged. This is the
* equivalent of what schema() returned in SimpleSchema < 2.0
*
* Note that this returns the raw, unevaluated definition object. Use `getDefinition`
* if you want the evaluated definition, where any properties that are functions
* have been run to produce a result.
*/
mergedSchema (): SchemaDefinition {
const mergedSchema: SchemaDefinition = {}
this._schemaKeys.forEach((key) => {
const keySchema = this._schema[key]
mergedSchema[key] = keySchema
keySchema.type.definitions.forEach((typeDef) => {
if (!SimpleSchema.isSimpleSchema(typeDef.type)) return
const childSchema = (typeDef.type as SimpleSchema).mergedSchema()
Object.keys(childSchema).forEach((subKey) => {
mergedSchema[`${key}.${subKey}`] = childSchema[subKey]
})
})
})
return mergedSchema
}
/**
* Returns the evaluated definition for one key in the schema
*
* @param key Generic or specific schema key
* @param [propList] Array of schema properties you need; performance optimization
* @param [functionContext] The context to use when evaluating schema options that are functions
* @returns The schema definition for the requested key
*/
getDefinition (
key: string,
propList?: string[] | null,
functionContext: Record<string, unknown> = {}
): StandardSchemaKeyDefinitionWithSimpleTypes | undefined {
const schemaKeyDefinition = this.schema(key)
if (schemaKeyDefinition == null) return
return this.resolveDefinitionForSchema(key, schemaKeyDefinition, propList, functionContext)
}
/**
* Returns the evaluated definition for one key in the schema
*
* @param key Generic or specific schema key
* @param [propList] Array of schema properties you need; performance optimization
* @param [functionContext] The context to use when evaluating schema options that are functions
* @returns The schema definition for the requested key
*/
getDefinitions (
key: string,
propList?: string[] | null,
functionContext: Record<string, unknown> = {}
): StandardSchemaKeyDefinitionWithSimpleTypes[] {
const schemaKeyDefinitions = this.schemas(key)
return schemaKeyDefinitions.map((def) => {
return this.resolveDefinitionForSchema(key, def, propList, functionContext)
})
}
/**
* Resolves the definition for one key in the schema
*
* @param key Generic or specific schema key
* @param schemaKeyDefinition Unresolved definition as returned from simpleSchema.schema()
* @param [propList] Array of schema properties you need; performance optimization
* @param [functionContext] The context to use when evaluating schema options that are functions
* @returns The schema definition for the requested key
*/
resolveDefinitionForSchema (
key: string,
schemaKeyDefinition: StandardSchemaKeyDefinition,
propList?: string[] | null,
functionContext: Record<string, unknown> = {}
): StandardSchemaKeyDefinitionWithSimpleTypes {
const getPropIterator = (obj: Record<string, any>, newObj: Record<string, any>) => {
return (prop: string): void => {
if (Array.isArray(propList) && !propList.includes(prop)) return
const val = obj[prop]
// For any options that support specifying a function, evaluate the functions
if (
propsThatCanBeFunction.includes(prop) &&
typeof val === 'function'
) {
newObj[prop] = val.call({
key,
...functionContext
})
// Inflect label if undefined
if (prop === 'label' && typeof newObj.label !== 'string') {
newObj.label = inflectedLabel(
key,
this._constructorOptions.humanizeAutoLabels
)
}
} else {
newObj[prop] = val
}
}
}
const result: StandardSchemaKeyDefinitionWithSimpleTypes = {
type: []
}
Object.keys(schemaKeyDefinition).forEach(getPropIterator(schemaKeyDefinition, result))
// Resolve all the types and convert to a normal array to make it easier to use.
if (Array.isArray(schemaKeyDefinition.type?.definitions)) {
result.type = schemaKeyDefinition.type.definitions.map((typeDef) => {
const newTypeDef: SchemaKeyDefinitionWithOneType = {
type: String // will be overwritten
}
Object.keys(typeDef).forEach(getPropIterator(typeDef, newTypeDef))
return newTypeDef
})
}
return result
}
/**
* Returns a string identifying the best guess data type for a key. For keys
* that allow multiple types, the first type is used. This can be useful for
* building forms.
*
* @param key Generic or specific schema key
* @returns A type string. One of:
* string, number, boolean, date, object, stringArray, numberArray, booleanArray,
* dateArray, objectArray
*/
getQuickTypeForKey (key: string): string | undefined {
let type
const fieldSchema = this.schema(key)
if (fieldSchema == null) return
const fieldType = (fieldSchema.type).singleType
if (fieldType === String) {
type = 'string'
} else if (fieldType === Number || fieldType === SimpleSchema.Integer) {
type = 'number'
} else if (fieldType === Boolean) {
type = 'boolean'
} else if (fieldType === Date) {
type = 'date'
} else if (fieldType === Array) {
const arrayItemFieldSchema = this.schema(`${key}.$`)
if (arrayItemFieldSchema == null) return
const arrayItemFieldType = (arrayItemFieldSchema.type).singleType
if (arrayItemFieldType === String) {
type = 'stringArray'
} else if (
arrayItemFieldType === Number ||
arrayItemFieldType === SimpleSchema.Integer
) {
type = 'numberArray'
} else if (arrayItemFieldType === Boolean) {
type = 'booleanArray'
} else if (arrayItemFieldType === Date) {
type = 'dateArray'
} else if (
arrayItemFieldType === Object ||
SimpleSchema.isSimpleSchema(arrayItemFieldType)
) {
type = 'objectArray'
}
} else if (fieldType === Object) {
type = 'object'
}
return type
}
/**
* Given a key that is an Object, returns a new SimpleSchema instance scoped to that object.
*
* @param key Generic or specific schema key
*/
getObjectSchema (key: string): SimpleSchema {
const newSchemaDef: SchemaDefinition = {}
const genericKey = MongoObject.makeKeyGeneric(key)
if (genericKey == null) throw new Error(`Unable to make a generic key for ${key}`)
const searchString = `${genericKey}.`
const mergedSchema = this.mergedSchema()
Object.keys(mergedSchema).forEach((k) => {
if (k.indexOf(searchString) === 0) {
newSchemaDef[k.slice(searchString.length)] = mergedSchema[k]
}
})
return this._copyWithSchema(newSchemaDef)
}
// Returns an array of all the autovalue functions, including those in subschemas all the
// way down the schema tree
autoValueFunctions (): AutoValueFunctionDetails[] {
const result: AutoValueFunctionDetails[] = [...this._autoValues]
this._schemaKeys.forEach((key) => {
this._schema[key].type.definitions.forEach((typeDef) => {
if (!SimpleSchema.isSimpleSchema(typeDef.type)) return
result.push(
...(typeDef.type as SimpleSchema)
.autoValueFunctions()
.map(({ func, fieldName, closestSubschemaFieldName }) => {
return {
func,
fieldName: `${key}.${fieldName}`,
closestSubschemaFieldName: closestSubschemaFieldName.length > 0
? `${key}.${closestSubschemaFieldName}`
: key
}
})
)
})
})
return result
}
// Returns an array of all the blackbox keys, including those in subschemas
blackboxKeys (): string[] {
const blackboxKeys = new Set(this._blackboxKeys)
this._schemaKeys.forEach((key) => {
this._schema[key].type.definitions.forEach((typeDef) => {
if (!SimpleSchema.isSimpleSchema(typeDef.type)) return;
(typeDef.type as SimpleSchema).blackboxKeys().forEach((blackboxKey) => {
blackboxKeys.add(`${key}.${blackboxKey}`)
})
})
})
return Array.from(blackboxKeys)
}
/**
* Check if the key is a nested dot-syntax key inside of a blackbox object
* @param key Key to check
* @returns True if key is in a black box object
*/
keyIsInBlackBox (key: string): boolean {
const genericKey = MongoObject.makeKeyGeneric(key)
if (genericKey == null) return false
let isInBlackBox = false
forEachKeyAncestor(
genericKey,
(ancestor, remainder) => {
if (this._blackboxKeys.has(ancestor)) {
isInBlackBox = true
} else {
const testKeySchema = this.schema(ancestor)
if (testKeySchema != null) {
testKeySchema.type.definitions.forEach((typeDef) => {
if (!SimpleSchema.isSimpleSchema(typeDef.type)) return
if ((typeDef.type as SimpleSchema).keyIsInBlackBox(remainder)) isInBlackBox = true
})
}
}
}
)
return isInBlackBox
}
// Returns true if key is explicitly allowed by the schema or implied
// by other explicitly allowed keys.
// The key string should have $ in place of any numeric array positions.
allowsKey (key: string): boolean {
// Loop through all keys in the schema
return this._schemaKeys.some((loopKey) => {
// If the schema key is the test key, it's allowed.
if (loopKey === key) return true
const compare1 = key.slice(0, loopKey.length + 2)
const compare2 = compare1.slice(0, -1)
// Blackbox and subschema checks are needed only if key starts with
// loopKey + a dot
if (compare2 !== `${loopKey}.`) return false
// Black box handling
if (this._blackboxKeys.has(loopKey)) {
// If the test key is the black box key + ".$", then the test
// key is NOT allowed because black box keys are by definition
// only for objects, and not for arrays.
return compare1 !== `${loopKey}.$`
}
// Subschemas
let allowed = false
const subKey = key.slice(loopKey.length + 1)
this.schema(loopKey)?.type.definitions.forEach((typeDef) => {
if (!SimpleSchema.isSimpleSchema(typeDef.type)) return
if ((typeDef.type as SimpleSchema).allowsKey(subKey)) allowed = true
})
return allowed
})
}
/**
* Returns all the child keys for the object identified by the generic prefix,
* or all the top level keys if no prefix is supplied.
*
* @param [keyPrefix] The Object-type generic key for which to get child keys. Omit for
* top-level Object-type keys
* @returns Array of child keys for the given object key
*/
objectKeys (keyPrefix?: string): string[] {
if (keyPrefix == null) return this._firstLevelSchemaKeys
const objectKeys: Record<string, string[]> = {}
const setObjectKeys = (curSchema: ResolvedSchemaDefinition, schemaParentKey?: string): void => {
Object.keys(curSchema).forEach((fieldName) => {
const definition = curSchema[fieldName]
fieldName = schemaParentKey != null ? `${schemaParentKey}.${fieldName}` : fieldName
if (fieldName.includes('.') && fieldName.slice(-2) !== '.$') {
const parentKey = fieldName.slice(0, fieldName.lastIndexOf('.'))
const parentKeyWithDot = `${parentKey}.`
objectKeys[parentKeyWithDot] = objectKeys[parentKeyWithDot] ?? []
objectKeys[parentKeyWithDot].push(fieldName.slice(fieldName.lastIndexOf('.') + 1))
}
// If the current field is a nested SimpleSchema,
// iterate over the child fields and cache their properties as well
definition.type.definitions.forEach(({ type }) => {
if (SimpleSchema.isSimpleSchema(type)) {
setObjectKeys((type as SimpleSchema)._schema, fieldName)
}
})
})
}
setObjectKeys(this._schema)
return objectKeys[`${keyPrefix}.`] ?? []
}
/**
* Copies this schema into a new instance with the same validators, messages,
* and options, but with different keys as defined in `schema` argument
*
* @param schema
* @returns The new SimpleSchema instance (chainable)
*/
_copyWithSchema (schema: SchemaDefinition): SimpleSchema {
const cl = new SimpleSchema(schema, { ...this._constructorOptions })
cl._cleanOptions = this._cleanOptions
return cl
}
/**
* Clones this schema into a new instance with the same schema keys, validators,
* and options.
*
* @returns The new SimpleSchema instance (chainable)
*/
clone (): SimpleSchema {
return this._copyWithSchema(this._schema)
}
/**
* Extends (mutates) this schema with another schema, key by key.
*
* @param schema The schema or schema definition to extend onto this one
* @returns The SimpleSchema instance (chainable)
*/
extend (schema: SimpleSchema | PartialSchemaDefinitionWithShorthand = {}): SimpleSchema {
if (Array.isArray(schema)) {
throw new Error(
'You may not pass an array of schemas to the SimpleSchema constructor or to extend()'
)
}
let schemaObj: SchemaDefinition
if (SimpleSchema.isSimpleSchema(schema)) {
schemaObj = (schema as SimpleSchema)._schema
this._validators = this._validators.concat((schema as SimpleSchema)._validators)
this._docValidators = this._docValidators.concat((schema as SimpleSchema)._docValidators)
Object.assign(this._cleanOptions, (schema as SimpleSchema)._cleanOptions)
Object.assign(this._constructorOptions, (schema as SimpleSchema)._constructorOptions)
} else {
schemaObj = expandShorthand(schema as SchemaDefinitionWithShorthand)
}
const schemaKeys = Object.keys(schemaObj)
const combinedKeys = new Set([...Object.keys(this._schema), ...schemaKeys])
// Update all of the information cached on the instance
schemaKeys.forEach((fieldName) => {
const definition = standardizeDefinition(schemaObj[fieldName])
// Merge/extend with any existing definition
if (this._schema[fieldName] != null) {
if (!Object.prototype.hasOwnProperty.call(this._schema, fieldName)) {
// fieldName is actually a method from Object itself!
throw new Error(
`${fieldName} key is actually the name of a method on Object, please rename it`
)
}
const { type, ...definitionWithoutType } = definition // eslint-disable-line no-unused-vars
this._schema[fieldName] = {
...this._schema[fieldName],
...definitionWithoutType
}
if (definition.type != null) { this._schema[fieldName].type.extend(definition.type) }
} else {
this._schema[fieldName] = definition
}
checkAndScrubDefinition(
fieldName,
this._schema[fieldName],
this._constructorOptions,
combinedKeys
)
})
checkSchemaOverlap(this._schema)
// Set/Reset all of these
this._schemaKeys = Object.keys(this._schema)
this._autoValues = []
this._blackboxKeys = new Set()
this._firstLevelSchemaKeys = []
// Update all of the information cached on the instance
this._schemaKeys.forEach((fieldName) => {
// Make sure parent has a definition in the schema. No implied objects!
if (fieldName.includes('.')) {
const parentFieldName = fieldName.slice(0, fieldName.lastIndexOf('.'))
if (
!Object.prototype.hasOwnProperty.call(this._schema, parentFieldName)
) {
throw new Error(
`"${fieldName}" is in the schema but "${parentFieldName}" is not`
)
}
}
const definition = this._schema[fieldName]
// Keep list of all top level keys
if (!fieldName.includes('.')) { this._firstLevelSchemaKeys.push(fieldName) }
// Keep list of all blackbox keys for passing to MongoObject constructor
// XXX For now if any oneOf type is blackbox, then the whole field is.
/* eslint-disable no-restricted-syntax */
for (const oneOfDef of definition.type.definitions) {
// XXX If the type is SS.Any, also consider it a blackbox
if (oneOfDef.blackbox === true || oneOfDef.type === SimpleSchema.Any) {
this._blackboxKeys.add(fieldName)
break
}
}
/* eslint-enable no-restricted-syntax */
// Keep list of autoValue functions
if (typeof definition.autoValue === 'function') {
this._autoValues.push({
closestSubschemaFieldName: '',
fieldName,
func: definition.autoValue
})
}
})
return this
}
getAllowedValuesForKey (key: string): any[] | null {
// For array fields, `allowedValues` is on the array item definition
if (this.allowsKey(`${key}.$`)) {
key = `${key}.$`
}
const allowedValues = this.get(key, 'allowedValues')
if (Array.isArray(allowedValues) || allowedValues instanceof Set) {
return [...allowedValues]
}
return null
}
newContext (): ValidationContext {
return new ValidationContext(this)
}
namedContext (name?: string): ValidationContext {
if (typeof name !== 'string') name = 'default'
if (this._validationContexts[name] == null) {
this._validationContexts[name] = new ValidationContext(this, name)
}
return this._validationContexts[name]
}
addValidator (func: ValidatorFunction): void {
this._validators.push(func)
}
addDocValidator (func: DocValidatorFunction): void {
this._docValidators.push(func)
}
/**
* @param obj Object or array of objects to validate.
* @param options Same options object that ValidationContext#validate takes
*
* Throws an Error with name `ClientError` and `details` property containing the errors.
*/
validate (obj: any, options: ValidationOptions = {}): void {
// obj can be an array, in which case we validate each object in it and
// throw as soon as one has an error
const objects = Array.isArray(obj) ? obj : [obj]
objects.forEach((oneObj) => {
const validationContext = this.newContext()
const isValid = validationContext.validate(oneObj, options)
if (isValid) return
const errors = validationContext.validationErrors()
// In order for the message at the top of the stack trace to be useful,
// we set it to the first validation error message.
const message = this.messageForError(errors[0])
const error = new ClientError<ValidationError[]>(message, 'validation-error')
// Add meaningful error messages for each validation error.
// Useful for display messages when using 'mdg:validated-method'.
error.details = errors.map((errorDetail) => ({
...errorDetail,
message: this.messageForError(errorDetail)
}))
// The primary use for the validationErrorTransform is to convert the
// vanilla Error into a Meteor.Error until DDP is able to pass
// vanilla errors back to the client.
if (typeof SimpleSchema.validationErrorTransform === 'function') {
throw SimpleSchema.validationErrorTransform(error)
} else {
throw error
}
})
}
/**
* @param obj Object to validate.
* @param options Same options object that ValidationContext#validate takes
*
* Returns a Promise that resolves with the errors
*/
async validateAndReturnErrorsPromise (
obj: any,
options: ValidationOptions
): Promise<ValidationError[]> {
const validationContext = this.newContext()
const isValid = validationContext.validate(obj, options)
if (isValid) return []
// Add the `message` prop
return validationContext.validationErrors().map((errorDetail) => {
return { ...errorDetail, message: this.messageForError(errorDetail) }
})
}
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
validator (options: ValidationOptions & { clean?: boolean, returnErrorsPromise?: boolean } = {}): (obj: Record<string, any>) => void | Promise<ValidationError[]> {
return (obj: Record<string, any>) => {
const optionsClone = { ...options }
if (options.clean === true) {
// Do this here and pass into both functions for better performance
optionsClone.mongoObject = new MongoObject(obj, this.blackboxKeys())
this.clean(obj, optionsClone)
}
if (options.returnErrorsPromise === true) {
return this.validateAndReturnErrorsPromise(obj, optionsClone)
}
return this.validate(obj, optionsClone)
}
}
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
getFormValidator (options = {}): (obj: Record<string, any>) => void | Promise<ValidationError[]> {
return this.validator({ ...options, returnErrorsPromise: true })
}
clean (doc: Record<string | number | symbol, unknown>, options: CleanOptions = {}): Record<string | number | symbol, unknown> {
return clean(this, doc, options)
}
/**
* Change schema labels on the fly. Useful when the user changes the language.
*
* @param labels A dictionary of all the new label values, by schema key.
*/
labels (labels: Record<string, string | (() => string)>): void {
for (const [key, label] of Object.entries(labels)) {
if (typeof label !== 'string' && typeof label !== 'function') continue
// Support setting labels that were actually originally defined in a sub-schema
const [schemaInstance, innerKey] = this.nearestSimpleSchemaInstance(key)
if (schemaInstance == null || innerKey == null) continue
schemaInstance._schema[innerKey].label = label
}
}
/**
* Gets a field's label or all field labels reactively.
*
* @param key The schema key, specific or generic.
* Omit this argument to get a dictionary of all labels.
* @returns The label
*/
label (): Record<string, string>
label (key: string): string | null
label (key?: string): Record<string, string> | string | null {
// Get all labels
if (key === null || key === undefined) {
const result: Record<string, string> = {}
this._schemaKeys.forEach((schemaKey) => {
result[schemaKey] = this.label(schemaKey) as string
})
return result
}
// Get label for one field
const label = this.get(key, 'label') as string
return label ?? null
}
/**
* Gets a field's property
*
* @param key The schema key, specific or generic.
* @param prop Name of the property to get for that schema key
* @param functionContext The `this` context to use if prop is a function
* @returns The property value
*/
get (
key: string,
prop: keyof StandardSchemaKeyDefinitionWithSimpleTypes | keyof StandardSchemaKeyDefinition,
functionContext?: Record<string, unknown>
): any {
const def = this.getDefinition(key, ['type', prop], functionContext)
if (def == null) return undefined
if (schemaDefinitionOptions.includes(prop)) {
return def[prop as keyof StandardSchemaKeyDefinitionWithSimpleTypes]
}
const oneType = def.type[0]
if (oneType === SimpleSchema.Any) return undefined
return (oneType as SchemaKeyDefinitionWithOneType)?.[prop as keyof StandardSchemaKeyDefinition]
}
// shorthand for getting defaultValue
defaultValue (key: string): unknown {
return this.get(key, 'defaultValue')
}
// Returns a string message for the given error type and key.
// Defers to a user-provided getErrorMessage function, which
// can do custom messages and translations, or falls back to
// built-in English defaults.
messageForError (errorInfo: ValidationError): string {
const { name } = errorInfo
const label = this.label(name)