or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

data-cleaning.mdindex.mdschema-definition.mdschema-introspection.mdutility-functions.mdvalidation-context.mdvalidation.md
tile.json

tessl/npm-simpl-schema

A schema validation package that supports direct validation of MongoDB update modifier objects.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/simpl-schema@3.4.x

To install, run

npx @tessl/cli install tessl/npm-simpl-schema@3.4.0

index.mddocs/

SimpleSchema

SimpleSchema is a mature JavaScript/TypeScript schema validation library that provides comprehensive object validation with support for MongoDB update documents. It offers isomorphic functionality working in both NodeJS and modern browsers, with features including automatic type conversion, customizable error messages with localization support, object cleaning to fix potential validation errors automatically, and powerful autoValue/defaultValue systems.

Package Information

  • Package Name: simpl-schema
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install simpl-schema

Core Imports

import SimpleSchema, { ValidationContext, toJsonSchema } from "simpl-schema";

For CommonJS:

const SimpleSchema = require("simpl-schema").default;
const { ValidationContext, toJsonSchema } = require("simpl-schema");

Basic Usage

import SimpleSchema from "simpl-schema";

// Define a schema
const userSchema = new SimpleSchema({
  name: {
    type: String,
    min: 1,
    max: 200,
    label: "Full Name"
  },
  email: {
    type: String,
    regEx: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
    label: "Email Address"
  },
  age: {
    type: SimpleSchema.Integer,
    min: 0,
    max: 200,
    optional: true
  }
});

// Validate an object
const user = { name: "John Doe", email: "john@example.com", age: 30 };
userSchema.validate(user); // Throws error if invalid

// Or use validation context for error collection
const context = userSchema.newContext();
const isValid = context.validate(user);
if (!isValid) {
  console.log(context.validationErrors());
}

// Clean and validate
const cleanedUser = userSchema.clean(user);
userSchema.validate(cleanedUser);

Architecture

SimpleSchema is built around several key components:

  • SimpleSchema Class: Main schema definition and validation engine with extensive configuration options
  • ValidationContext: Manages validation state and error collection for detailed error reporting
  • Type System: Supports all JavaScript types plus special types like Integer and Any with full TypeScript integration
  • Cleaning System: Automatic type conversion, trimming, filtering, and value assignment before validation
  • MongoDB Integration: Native support for validating MongoDB update modifier documents
  • Extensibility: Custom validators, error message systems, and schema extension capabilities

Capabilities

Schema Definition

Core schema creation and manipulation functionality including field definitions, type constraints, and schema composition.

class SimpleSchema {
  constructor(
    definition: SchemaDefinitionWithShorthand,
    options?: SimpleSchemaOptions
  );
  
  extend(schema: SimpleSchema | PartialSchemaDefinitionWithShorthand): SimpleSchema;
  clone(): SimpleSchema;
  pick(...fields: string[]): SimpleSchema;
  omit(...fields: string[]): SimpleSchema;
}

interface SimpleSchemaOptions {
  clean?: CleanOptions;
  defaultLabel?: string;
  getErrorMessage?: GetErrorMessageFn;
  humanizeAutoLabels?: boolean;
  keepRawDefinition?: boolean;
  requiredByDefault?: boolean;
}

Schema Definition

Validation

Comprehensive validation system supporting object validation, MongoDB modifiers, custom validators, and detailed error reporting.

// Instance validation methods
validate(obj: any, options?: ValidationOptions): void;
validator(options?: ValidationOptions & {clean?: boolean, returnErrorsPromise?: boolean}): Function;
newContext(): ValidationContext;
namedContext(name?: string): ValidationContext;

// Static validation method
static validate(obj: any, schema: SimpleSchema | SchemaDefinition, options?: ValidationOptions): void;

interface ValidationOptions {
  extendedCustomContext?: Record<string | number | symbol, unknown>;
  ignore?: string[];
  keys?: string[];
  modifier?: boolean;
  mongoObject?: any;
  upsert?: boolean;
}

Validation

Data Cleaning

Automatic data cleaning and normalization including type conversion, trimming, filtering, and automatic value assignment.

clean(doc: Record<string | number | symbol, unknown>, options?: CleanOptions): Record<string | number | symbol, unknown>;

interface CleanOptions {
  autoConvert?: boolean;
  extendAutoValueContext?: CustomAutoValueContext;
  filter?: boolean;
  getAutoValues?: boolean;
  isModifier?: boolean;
  isUpsert?: boolean;
  mongoObject?: MongoObject;
  mutate?: boolean;
  removeEmptyStrings?: boolean;
  removeNullsFromArrays?: boolean;
  trimStrings?: boolean;
}

Data Cleaning

Validation Context

Validation context management for collecting validation errors, checking validity, and providing detailed error information.

class ValidationContext {
  validate(obj: ObjectToValidate, options?: ValidationOptions): boolean;
  isValid(): boolean;
  validationErrors(): ValidationError[];
  setValidationErrors(errors: ValidationError[]): void;
  addValidationErrors(errors: ValidationError[]): void;
  reset(): void;
  getErrorForKey(key: string, genericKey?: string): ValidationError | undefined;
  keyIsInvalid(key: string, genericKey?: string): boolean;
  keyErrorMessage(key: string, genericKey?: string): string;
  clean(doc: Record<string | number | symbol, unknown>, options?: CleanOptions): Record<string | number | symbol, unknown>;
}

Validation Context

Schema Introspection

Methods for examining schema structure, accessing field definitions, and navigating schema hierarchies.

schema(): ResolvedSchemaDefinition;
schema(key: string): StandardSchemaKeyDefinition | null;
getDefinition(key: string, propList?: string[], functionContext?: Record<string, unknown>): StandardSchemaKeyDefinitionWithSimpleTypes;
objectKeys(keyPrefix?: string): string[];
allowsKey(key: string): boolean;
getQuickTypeForKey(key: string): string;
getAllowedValuesForKey(key: string): any[] | null;
label(key: string): string | null;
defaultValue(key: string): unknown;

Schema Introspection

Utility Functions

Utility functions for schema conversion, type checking, and advanced schema operations.

// JSON Schema conversion
function toJsonSchema(simpleSchema: SimpleSchema, id?: string): JSONSchema7;

// Type checking and schema groups
static isSimpleSchema(obj: unknown): boolean;
static oneOf(...definitions): SimpleSchemaGroup;

class SimpleSchemaGroup {
  definitions: SchemaKeyDefinitionWithOneType[];
  singleType: SupportedTypes;
  clone(): SimpleSchemaGroup;
  extend(otherGroup: SimpleSchemaGroup): void;
}

Utility Functions

Types

// Core validation types
interface ValidationError {
  message?: string;
  name: string;
  type: string;
  value: any;
  [prop: string]: any;
}

// Schema definition types
type SchemaDefinitionWithShorthand = Record<string, SchemaKeyDefinitionWithShorthand>;
type SchemaKeyDefinitionWithShorthand = StandardSchemaKeyDefinition | SchemaKeyDefinitionWithOneType | SupportedTypes | RegExpConstructor | SimpleSchemaGroup | SupportedTypes[];

interface SchemaKeyDefinitionBase {
  autoValue?: AutoValueFunction;
  defaultValue?: any;
  label?: string | ((this: FunctionOptionContext) => string);
  optional?: boolean | (() => boolean);
  required?: boolean | (() => boolean);
  
  // Type validation properties
  allowedValues?: AllowedValues | (() => AllowedValues);
  blackbox?: boolean;
  custom?: ValidatorFunction;
  exclusiveMax?: boolean;
  exclusiveMin?: boolean;
  maxCount?: number;
  max?: number | Date | (() => number | Date);
  minCount?: number;
  min?: number | Date | (() => number | Date);
  regEx?: RegExp | RegExp[];
  skipRegExCheckForEmptyStrings?: boolean;
  trim?: boolean;
}

interface SchemaKeyDefinitionWithOneType extends SchemaKeyDefinitionBase {
  type: SupportedTypes;
}

// Supported types
type SupportedTypes = 
  | ArrayConstructor
  | BooleanConstructor
  | DateConstructor
  | NumberConstructor
  | StringConstructor
  | ObjectConstructor
  | '___Any___'
  | typeof SimpleSchema.Integer
  | SimpleSchema
  | AnyClass
  | RegExp;

// Function types
type AutoValueFunction = (this: AutoValueContext, obj: any) => any;
type ValidatorFunction = (this: ValidatorContext) => void | undefined | boolean | string | ValidationErrorResult;
type DocValidatorFunction = (this: DocValidatorContext, obj: Record<string, unknown>) => ValidationError[];

// Context types for validation functions
interface AutoValueContext {
  key: string;
  siblingKey: string;
  parentKey: string;
  isSet: boolean;
  value: any;
  operator: string;
  field: (key: string) => { isSet: boolean; value: any; operator: string | null };
  siblingField: (key: string) => { isSet: boolean; value: any; operator: string | null };
  [prop: string]: any;
}

interface ValidatorContext {
  key: string;
  keyToValidate: string;
  genericKey: string;
  definition: StandardSchemaKeyDefinition;
  isSet: boolean;
  value: any;
  operator: string;
  validationContext: ValidationContext;
  field: (key: string) => { isSet: boolean; value: any; operator: string | null };
  siblingField: (key: string) => { isSet: boolean; value: any; operator: string | null };
  [prop: string]: any;
}

interface DocValidatorContext {
  isModifier: boolean;
  isUpsert: boolean;
  userId: string | null;
  [prop: string]: any;
}

interface ValidationErrorResult {
  type: string;
  message?: string;
  [prop: string]: any;
}

// Additional utility types
type AllowedValues = any[] | Set<any>;
type AnyClass = new (...args: any[]) => any;

interface FunctionOptionContext {
  key?: string | null;
  [prop: string]: unknown;
}

interface ClientError<T> {
  error: {
    type: string;
    name: string;
    [prop: string]: any;
  };
  details?: T;
  [prop: string]: any;
}