0
# Utility Functions
1
2
Utility functions for schema conversion, type checking, and advanced schema operations.
3
4
## Capabilities
5
6
### JSON Schema Conversion
7
8
Convert SimpleSchema instances to JSON Schema format for interoperability.
9
10
```typescript { .api }
11
/**
12
* Converts a SimpleSchema instance to JSON Schema Document format
13
* @param simpleSchema - SimpleSchema instance to convert
14
* @param id - Optional schema ID for the JSON Schema document
15
* @returns JSON Schema Document (JSONSchema7 format)
16
*/
17
function toJsonSchema(simpleSchema: SimpleSchema, id?: string): JSONSchema7;
18
19
interface JSONSchema7 {
20
$schema?: string;
21
$id?: string;
22
type?: string;
23
properties?: Record<string, JSONSchema7>;
24
required?: string[];
25
additionalProperties?: boolean | JSONSchema7;
26
// ... other JSON Schema properties
27
}
28
```
29
30
**Usage Examples:**
31
32
```typescript
33
import SimpleSchema, { toJsonSchema } from "simpl-schema";
34
35
const userSchema = new SimpleSchema({
36
name: {
37
type: String,
38
min: 1,
39
max: 100,
40
label: "Full Name"
41
},
42
email: {
43
type: String,
44
regEx: SimpleSchema.RegEx.Email
45
},
46
age: {
47
type: SimpleSchema.Integer,
48
min: 0,
49
max: 120,
50
optional: true
51
},
52
tags: [String],
53
profile: {
54
type: Object,
55
optional: true
56
},
57
'profile.bio': {
58
type: String,
59
max: 500,
60
optional: true
61
}
62
});
63
64
// Convert to JSON Schema
65
const jsonSchema = toJsonSchema(userSchema);
66
console.log(jsonSchema);
67
// {
68
// type: "object",
69
// properties: {
70
// name: {
71
// type: "string",
72
// minLength: 1,
73
// maxLength: 100,
74
// title: "Full Name"
75
// },
76
// email: {
77
// type: "string",
78
// format: "email"
79
// },
80
// age: {
81
// type: "integer",
82
// minimum: 0,
83
// maximum: 120
84
// },
85
// tags: {
86
// type: "array",
87
// items: { type: "string" }
88
// },
89
// profile: {
90
// type: "object",
91
// properties: {
92
// bio: {
93
// type: "string",
94
// maxLength: 500
95
// }
96
// }
97
// }
98
// },
99
// required: ["name", "email", "tags"]
100
// }
101
102
// Convert with custom schema ID
103
const jsonSchemaWithId = toJsonSchema(userSchema, "https://example.com/user-schema");
104
console.log(jsonSchemaWithId.$id); // "https://example.com/user-schema"
105
```
106
107
### Type Checking Utilities
108
109
Utility functions for type checking and schema identification.
110
111
```typescript { .api }
112
/**
113
* Tests if an object is a SimpleSchema instance
114
* @param obj - Object to test
115
* @returns true if object is SimpleSchema instance
116
*/
117
static isSimpleSchema(obj: unknown): boolean;
118
```
119
120
**Usage Examples:**
121
122
```typescript
123
import SimpleSchema from "simpl-schema";
124
125
const userSchema = new SimpleSchema({ name: String });
126
const regularObject = { name: String };
127
const plainObject = {};
128
129
console.log(SimpleSchema.isSimpleSchema(userSchema)); // true
130
console.log(SimpleSchema.isSimpleSchema(regularObject)); // false
131
console.log(SimpleSchema.isSimpleSchema(plainObject)); // false
132
console.log(SimpleSchema.isSimpleSchema(null)); // false
133
console.log(SimpleSchema.isSimpleSchema(undefined)); // false
134
135
// Useful for type guards
136
function processSchema(input: unknown) {
137
if (SimpleSchema.isSimpleSchema(input)) {
138
// TypeScript now knows input is SimpleSchema
139
const keys = input.objectKeys();
140
console.log('Schema keys:', keys);
141
} else {
142
console.log('Not a SimpleSchema instance');
143
}
144
}
145
```
146
147
### Schema Groups and Union Types
148
149
Create and manage union types that allow multiple type options for fields.
150
151
```typescript { .api }
152
/**
153
* Creates a schema group representing a union of multiple types
154
* @param definitions - Type definitions to allow as alternatives
155
* @returns SimpleSchemaGroup instance representing the union type
156
*/
157
static oneOf(...definitions): SimpleSchemaGroup;
158
159
/**
160
* SimpleSchemaGroup class for managing union types
161
*/
162
class SimpleSchemaGroup {
163
/** Array of type definitions in this group */
164
definitions: SchemaKeyDefinitionWithOneType[];
165
166
/** First type in the definitions (getter method) */
167
singleType: SupportedTypes;
168
169
/**
170
* Creates a copy of the schema group
171
* @returns New SimpleSchemaGroup instance with same definitions
172
*/
173
clone(): SimpleSchemaGroup;
174
175
/**
176
* Extends this group with definitions from another group
177
* @param otherGroup - SimpleSchemaGroup to merge with this one
178
*/
179
extend(otherGroup: SimpleSchemaGroup): void;
180
}
181
182
interface SchemaKeyDefinitionWithOneType {
183
type: SupportedTypes;
184
// ... other field properties
185
}
186
```
187
188
**Usage Examples:**
189
190
```typescript
191
import SimpleSchema from "simpl-schema";
192
193
// Create union types with oneOf
194
const flexibleSchema = new SimpleSchema({
195
identifier: SimpleSchema.oneOf(String, Number),
196
197
contact: SimpleSchema.oneOf(
198
{ type: String, regEx: SimpleSchema.RegEx.Email }, // Email
199
{ type: String, regEx: /^\+?[1-9]\d{1,14}$/ } // Phone
200
),
201
202
priority: SimpleSchema.oneOf(
203
{ type: String, allowedValues: ['low', 'medium', 'high'] },
204
{ type: Number, min: 1, max: 10 }
205
)
206
});
207
208
// Test validation with union types
209
flexibleSchema.validate({
210
identifier: "user123", // String - valid
211
contact: "user@email.com", // Email format - valid
212
priority: "high" // String from allowed values - valid
213
});
214
215
flexibleSchema.validate({
216
identifier: 12345, // Number - valid
217
contact: "+1234567890", // Phone format - valid
218
priority: 8 // Number in range - valid
219
});
220
221
// Working with SimpleSchemaGroup directly
222
const stringOrNumber = SimpleSchema.oneOf(String, Number);
223
console.log(stringOrNumber.definitions.length); // 2
224
console.log(stringOrNumber.singleType); // StringConstructor (first type)
225
226
// Clone a schema group
227
const clonedGroup = stringOrNumber.clone();
228
console.log(clonedGroup !== stringOrNumber); // true - different instance
229
230
// Extend a schema group
231
const extendedGroup = SimpleSchema.oneOf(String);
232
extendedGroup.extend(SimpleSchema.oneOf(Number, Boolean));
233
console.log(extendedGroup.definitions.length); // 3 (String, Number, Boolean)
234
```
235
236
### Global Configuration Utilities
237
238
Utilities for managing global schema configuration.
239
240
```typescript { .api }
241
/**
242
* Extends the list of allowed schema definition options globally
243
* @param options - Array of additional option names to allow
244
*/
245
static extendOptions(options: string[]): void;
246
247
/**
248
* Sets global error transformation function
249
* @param transform - Function to transform validation errors
250
*/
251
static defineValidationErrorTransform(transform: (error: ClientError<ValidationError[]>) => Error): void;
252
253
/**
254
* Gets or sets global constructor option defaults
255
* @param options - Optional new defaults to set
256
* @returns Current global constructor defaults
257
*/
258
static constructorOptionDefaults(options?: SimpleSchemaOptions): SimpleSchemaOptions | undefined;
259
260
/**
261
* Adds a global validator function that applies to all schema instances
262
* @param func - Validator function to add globally
263
*/
264
static addValidator(func: ValidatorFunction): void;
265
266
/**
267
* Adds a global document validator function that applies to all schema instances
268
* @param func - Document validator function to add globally
269
*/
270
static addDocValidator(func: DocValidatorFunction): void;
271
272
// Global configuration constants
273
static supportedConstructorOptions: Set<string>;
274
static supportedCleanOptions: Set<string>;
275
```
276
277
**Usage Examples:**
278
279
```typescript
280
import SimpleSchema from "simpl-schema";
281
282
// Extend allowed schema options globally
283
SimpleSchema.extendOptions(['customProp', 'anotherOption']);
284
285
// Now you can use the new options in schemas
286
const schema = new SimpleSchema({
287
name: {
288
type: String,
289
customProp: 'custom value', // Won't cause error anymore
290
anotherOption: true
291
}
292
});
293
294
// Set global error transformation
295
SimpleSchema.defineValidationErrorTransform(function(error) {
296
// Custom error transformation logic
297
// Must return an Error object
298
const transformedError = new Error(`Custom: ${error.error.type} error for ${error.error.name}`);
299
transformedError.name = error.error.name;
300
return transformedError;
301
});
302
303
// Add global validators
304
SimpleSchema.addValidator(function() {
305
// 'this' context provides validator context
306
if (this.key === 'username' && typeof this.value === 'string') {
307
if (this.value.length < 3) {
308
return 'Username must be at least 3 characters';
309
}
310
}
311
});
312
313
SimpleSchema.addDocValidator(function(obj) {
314
// Document-level validation across multiple fields
315
const errors = [];
316
if (obj.startDate && obj.endDate && obj.startDate > obj.endDate) {
317
errors.push({
318
name: 'endDate',
319
type: 'invalidDate',
320
value: obj.endDate,
321
message: 'End date must be after start date'
322
});
323
}
324
return errors;
325
});
326
327
// Set global constructor defaults
328
SimpleSchema.constructorOptionDefaults({
329
humanizeAutoLabels: true,
330
requiredByDefault: false
331
});
332
333
// Get current defaults
334
const defaults = SimpleSchema.constructorOptionDefaults();
335
console.log(defaults.humanizeAutoLabels); // true
336
337
// Check supported options
338
console.log(SimpleSchema.supportedConstructorOptions.has('clean')); // true
339
console.log(SimpleSchema.supportedCleanOptions.has('filter')); // true
340
```
341
342
### Constants and Special Types
343
344
Special type constants and error type definitions.
345
346
```typescript { .api }
347
// Special type constants
348
static Any: '___Any___'; // Allows any type
349
static Integer: 'SimpleSchema.Integer'; // Integer numbers only
350
static version: number; // Library version (value: 2)
351
352
// Error type constants
353
static ErrorTypes: Record<string, string>;
354
355
```
356
357
**Usage Examples:**
358
359
```typescript
360
import SimpleSchema from "simpl-schema";
361
362
// Using special type constants
363
const flexibleSchema = new SimpleSchema({
364
anyValue: SimpleSchema.Any, // Accepts any type
365
count: SimpleSchema.Integer, // Only integers, not floats
366
score: Number // Any number including floats
367
});
368
369
// Test special types
370
flexibleSchema.validate({
371
anyValue: "string", // Valid - Any accepts anything
372
count: 42, // Valid - integer
373
score: 3.14 // Valid - any number
374
});
375
376
flexibleSchema.validate({
377
anyValue: { complex: "object" }, // Valid - Any accepts anything
378
count: 3.14, // Invalid - not an integer
379
score: 42 // Valid - integers are numbers too
380
});
381
382
// Using custom regex patterns for validation
383
const contactSchema = new SimpleSchema({
384
email: {
385
type: String,
386
regEx: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
387
},
388
website: {
389
type: String,
390
regEx: /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/,
391
optional: true
392
},
393
phone: {
394
type: String,
395
regEx: /^\+?[1-9]\d{1,14}$/,
396
optional: true
397
}
398
});
399
400
// Check library version
401
console.log(SimpleSchema.version); // 2
402
403
// Access error types
404
console.log(SimpleSchema.ErrorTypes.REQUIRED); // 'required'
405
console.log(SimpleSchema.ErrorTypes.MIN_STRING); // 'minString'
406
```
407
408
409
## Types
410
411
```typescript { .api }
412
interface JSONSchema7 {
413
$schema?: string;
414
$id?: string;
415
type?: string | string[];
416
properties?: Record<string, JSONSchema7>;
417
required?: string[];
418
additionalProperties?: boolean | JSONSchema7;
419
items?: JSONSchema7 | JSONSchema7[];
420
minLength?: number;
421
maxLength?: number;
422
minimum?: number;
423
maximum?: number;
424
format?: string;
425
title?: string;
426
description?: string;
427
// ... additional JSON Schema properties
428
}
429
430
interface SchemaKeyDefinitionWithOneType {
431
type: SupportedTypes;
432
allowedValues?: AllowedValues | (() => AllowedValues);
433
autoValue?: AutoValueFunction;
434
blackbox?: boolean;
435
custom?: ValidatorFunction;
436
defaultValue?: any;
437
exclusiveMax?: boolean;
438
exclusiveMin?: boolean;
439
label?: string | ((this: FunctionOptionContext) => string);
440
max?: number | Date | (() => number | Date);
441
maxCount?: number;
442
min?: number | Date | (() => number | Date);
443
minCount?: number;
444
optional?: boolean | (() => boolean);
445
regEx?: RegExp | RegExp[];
446
required?: boolean | (() => boolean);
447
skipRegExCheckForEmptyStrings?: boolean;
448
trim?: boolean;
449
}
450
451
type ObjectToValidate = Record<string | number | symbol, unknown>;
452
```