A schema validation package that supports direct validation of MongoDB update modifier objects.
—
Utility functions for schema conversion, type checking, and advanced schema operations.
Convert SimpleSchema instances to JSON Schema format for interoperability.
/**
* Converts a SimpleSchema instance to JSON Schema Document format
* @param simpleSchema - SimpleSchema instance to convert
* @param id - Optional schema ID for the JSON Schema document
* @returns JSON Schema Document (JSONSchema7 format)
*/
function toJsonSchema(simpleSchema: SimpleSchema, id?: string): JSONSchema7;
interface JSONSchema7 {
$schema?: string;
$id?: string;
type?: string;
properties?: Record<string, JSONSchema7>;
required?: string[];
additionalProperties?: boolean | JSONSchema7;
// ... other JSON Schema properties
}Usage Examples:
import SimpleSchema, { toJsonSchema } from "simpl-schema";
const userSchema = new SimpleSchema({
name: {
type: String,
min: 1,
max: 100,
label: "Full Name"
},
email: {
type: String,
regEx: SimpleSchema.RegEx.Email
},
age: {
type: SimpleSchema.Integer,
min: 0,
max: 120,
optional: true
},
tags: [String],
profile: {
type: Object,
optional: true
},
'profile.bio': {
type: String,
max: 500,
optional: true
}
});
// Convert to JSON Schema
const jsonSchema = toJsonSchema(userSchema);
console.log(jsonSchema);
// {
// type: "object",
// properties: {
// name: {
// type: "string",
// minLength: 1,
// maxLength: 100,
// title: "Full Name"
// },
// email: {
// type: "string",
// format: "email"
// },
// age: {
// type: "integer",
// minimum: 0,
// maximum: 120
// },
// tags: {
// type: "array",
// items: { type: "string" }
// },
// profile: {
// type: "object",
// properties: {
// bio: {
// type: "string",
// maxLength: 500
// }
// }
// }
// },
// required: ["name", "email", "tags"]
// }
// Convert with custom schema ID
const jsonSchemaWithId = toJsonSchema(userSchema, "https://example.com/user-schema");
console.log(jsonSchemaWithId.$id); // "https://example.com/user-schema"Utility functions for type checking and schema identification.
/**
* Tests if an object is a SimpleSchema instance
* @param obj - Object to test
* @returns true if object is SimpleSchema instance
*/
static isSimpleSchema(obj: unknown): boolean;Usage Examples:
import SimpleSchema from "simpl-schema";
const userSchema = new SimpleSchema({ name: String });
const regularObject = { name: String };
const plainObject = {};
console.log(SimpleSchema.isSimpleSchema(userSchema)); // true
console.log(SimpleSchema.isSimpleSchema(regularObject)); // false
console.log(SimpleSchema.isSimpleSchema(plainObject)); // false
console.log(SimpleSchema.isSimpleSchema(null)); // false
console.log(SimpleSchema.isSimpleSchema(undefined)); // false
// Useful for type guards
function processSchema(input: unknown) {
if (SimpleSchema.isSimpleSchema(input)) {
// TypeScript now knows input is SimpleSchema
const keys = input.objectKeys();
console.log('Schema keys:', keys);
} else {
console.log('Not a SimpleSchema instance');
}
}Create and manage union types that allow multiple type options for fields.
/**
* Creates a schema group representing a union of multiple types
* @param definitions - Type definitions to allow as alternatives
* @returns SimpleSchemaGroup instance representing the union type
*/
static oneOf(...definitions): SimpleSchemaGroup;
/**
* SimpleSchemaGroup class for managing union types
*/
class SimpleSchemaGroup {
/** Array of type definitions in this group */
definitions: SchemaKeyDefinitionWithOneType[];
/** First type in the definitions (getter method) */
singleType: SupportedTypes;
/**
* Creates a copy of the schema group
* @returns New SimpleSchemaGroup instance with same definitions
*/
clone(): SimpleSchemaGroup;
/**
* Extends this group with definitions from another group
* @param otherGroup - SimpleSchemaGroup to merge with this one
*/
extend(otherGroup: SimpleSchemaGroup): void;
}
interface SchemaKeyDefinitionWithOneType {
type: SupportedTypes;
// ... other field properties
}Usage Examples:
import SimpleSchema from "simpl-schema";
// Create union types with oneOf
const flexibleSchema = new SimpleSchema({
identifier: SimpleSchema.oneOf(String, Number),
contact: SimpleSchema.oneOf(
{ type: String, regEx: SimpleSchema.RegEx.Email }, // Email
{ type: String, regEx: /^\+?[1-9]\d{1,14}$/ } // Phone
),
priority: SimpleSchema.oneOf(
{ type: String, allowedValues: ['low', 'medium', 'high'] },
{ type: Number, min: 1, max: 10 }
)
});
// Test validation with union types
flexibleSchema.validate({
identifier: "user123", // String - valid
contact: "user@email.com", // Email format - valid
priority: "high" // String from allowed values - valid
});
flexibleSchema.validate({
identifier: 12345, // Number - valid
contact: "+1234567890", // Phone format - valid
priority: 8 // Number in range - valid
});
// Working with SimpleSchemaGroup directly
const stringOrNumber = SimpleSchema.oneOf(String, Number);
console.log(stringOrNumber.definitions.length); // 2
console.log(stringOrNumber.singleType); // StringConstructor (first type)
// Clone a schema group
const clonedGroup = stringOrNumber.clone();
console.log(clonedGroup !== stringOrNumber); // true - different instance
// Extend a schema group
const extendedGroup = SimpleSchema.oneOf(String);
extendedGroup.extend(SimpleSchema.oneOf(Number, Boolean));
console.log(extendedGroup.definitions.length); // 3 (String, Number, Boolean)Utilities for managing global schema configuration.
/**
* Extends the list of allowed schema definition options globally
* @param options - Array of additional option names to allow
*/
static extendOptions(options: string[]): void;
/**
* Sets global error transformation function
* @param transform - Function to transform validation errors
*/
static defineValidationErrorTransform(transform: (error: ClientError<ValidationError[]>) => Error): void;
/**
* Gets or sets global constructor option defaults
* @param options - Optional new defaults to set
* @returns Current global constructor defaults
*/
static constructorOptionDefaults(options?: SimpleSchemaOptions): SimpleSchemaOptions | undefined;
/**
* Adds a global validator function that applies to all schema instances
* @param func - Validator function to add globally
*/
static addValidator(func: ValidatorFunction): void;
/**
* Adds a global document validator function that applies to all schema instances
* @param func - Document validator function to add globally
*/
static addDocValidator(func: DocValidatorFunction): void;
// Global configuration constants
static supportedConstructorOptions: Set<string>;
static supportedCleanOptions: Set<string>;Usage Examples:
import SimpleSchema from "simpl-schema";
// Extend allowed schema options globally
SimpleSchema.extendOptions(['customProp', 'anotherOption']);
// Now you can use the new options in schemas
const schema = new SimpleSchema({
name: {
type: String,
customProp: 'custom value', // Won't cause error anymore
anotherOption: true
}
});
// Set global error transformation
SimpleSchema.defineValidationErrorTransform(function(error) {
// Custom error transformation logic
// Must return an Error object
const transformedError = new Error(`Custom: ${error.error.type} error for ${error.error.name}`);
transformedError.name = error.error.name;
return transformedError;
});
// Add global validators
SimpleSchema.addValidator(function() {
// 'this' context provides validator context
if (this.key === 'username' && typeof this.value === 'string') {
if (this.value.length < 3) {
return 'Username must be at least 3 characters';
}
}
});
SimpleSchema.addDocValidator(function(obj) {
// Document-level validation across multiple fields
const errors = [];
if (obj.startDate && obj.endDate && obj.startDate > obj.endDate) {
errors.push({
name: 'endDate',
type: 'invalidDate',
value: obj.endDate,
message: 'End date must be after start date'
});
}
return errors;
});
// Set global constructor defaults
SimpleSchema.constructorOptionDefaults({
humanizeAutoLabels: true,
requiredByDefault: false
});
// Get current defaults
const defaults = SimpleSchema.constructorOptionDefaults();
console.log(defaults.humanizeAutoLabels); // true
// Check supported options
console.log(SimpleSchema.supportedConstructorOptions.has('clean')); // true
console.log(SimpleSchema.supportedCleanOptions.has('filter')); // trueSpecial type constants and error type definitions.
// Special type constants
static Any: '___Any___'; // Allows any type
static Integer: 'SimpleSchema.Integer'; // Integer numbers only
static version: number; // Library version (value: 2)
// Error type constants
static ErrorTypes: Record<string, string>;Usage Examples:
import SimpleSchema from "simpl-schema";
// Using special type constants
const flexibleSchema = new SimpleSchema({
anyValue: SimpleSchema.Any, // Accepts any type
count: SimpleSchema.Integer, // Only integers, not floats
score: Number // Any number including floats
});
// Test special types
flexibleSchema.validate({
anyValue: "string", // Valid - Any accepts anything
count: 42, // Valid - integer
score: 3.14 // Valid - any number
});
flexibleSchema.validate({
anyValue: { complex: "object" }, // Valid - Any accepts anything
count: 3.14, // Invalid - not an integer
score: 42 // Valid - integers are numbers too
});
// Using custom regex patterns for validation
const contactSchema = new SimpleSchema({
email: {
type: String,
regEx: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
},
website: {
type: String,
regEx: /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/,
optional: true
},
phone: {
type: String,
regEx: /^\+?[1-9]\d{1,14}$/,
optional: true
}
});
// Check library version
console.log(SimpleSchema.version); // 2
// Access error types
console.log(SimpleSchema.ErrorTypes.REQUIRED); // 'required'
console.log(SimpleSchema.ErrorTypes.MIN_STRING); // 'minString'interface JSONSchema7 {
$schema?: string;
$id?: string;
type?: string | string[];
properties?: Record<string, JSONSchema7>;
required?: string[];
additionalProperties?: boolean | JSONSchema7;
items?: JSONSchema7 | JSONSchema7[];
minLength?: number;
maxLength?: number;
minimum?: number;
maximum?: number;
format?: string;
title?: string;
description?: string;
// ... additional JSON Schema properties
}
interface SchemaKeyDefinitionWithOneType {
type: SupportedTypes;
allowedValues?: AllowedValues | (() => AllowedValues);
autoValue?: AutoValueFunction;
blackbox?: boolean;
custom?: ValidatorFunction;
defaultValue?: any;
exclusiveMax?: boolean;
exclusiveMin?: boolean;
label?: string | ((this: FunctionOptionContext) => string);
max?: number | Date | (() => number | Date);
maxCount?: number;
min?: number | Date | (() => number | Date);
minCount?: number;
optional?: boolean | (() => boolean);
regEx?: RegExp | RegExp[];
required?: boolean | (() => boolean);
skipRegExCheckForEmptyStrings?: boolean;
trim?: boolean;
}
type ObjectToValidate = Record<string | number | symbol, unknown>;Install with Tessl CLI
npx tessl i tessl/npm-simpl-schema