CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-simpl-schema

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

Pending
Overview
Eval results
Files

schema-definition.mddocs/

Schema Definition

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

Capabilities

SimpleSchema Constructor

Creates a new SimpleSchema instance with field definitions and optional configuration.

/**
 * Creates a new SimpleSchema instance
 * @param definition - Schema field definitions with optional shorthand syntax
 * @param options - Optional configuration for the schema
 */
constructor(
  definition: SchemaDefinitionWithShorthand,
  options?: SimpleSchemaOptions
);

interface SimpleSchemaOptions {
  /** Clean options to apply by default when cleaning objects */
  clean?: CleanOptions;
  /** Default label to use for fields that don't have a label */
  defaultLabel?: string;
  /** Function to get custom error messages for validation errors */
  getErrorMessage?: GetErrorMessageFn;
  /** Whether to automatically humanize field names for labels */
  humanizeAutoLabels?: boolean;
  /** Whether to keep the raw definition for debugging purposes */
  keepRawDefinition?: boolean;
  /** Whether fields are required by default (default: false) */
  requiredByDefault?: boolean;
}

Schema Field Definitions

Define schema fields using shorthand or longhand syntax with type constraints and validation rules.

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

// Complete field definition interface
interface SchemaKeyDefinitionBase {
  /** Function to automatically set field value */
  autoValue?: AutoValueFunction;
  /** Default value for the field */
  defaultValue?: any;
  /** Human-readable label for the field */
  label?: string | ((this: FunctionOptionContext) => string);
  /** Whether the field is optional */
  optional?: boolean | (() => boolean);
  /** Whether the field is required */
  required?: boolean | (() => boolean);
  
  // Type validation properties
  /** Array or Set of allowed values */
  allowedValues?: AllowedValues | (() => AllowedValues);
  /** Whether to treat the field as a blackbox (skip validation of contents) */
  blackbox?: boolean;
  /** Custom validation function */
  custom?: ValidatorFunction;
  /** Whether max value is exclusive */
  exclusiveMax?: boolean;
  /** Whether min value is exclusive */
  exclusiveMin?: boolean;
  /** Maximum number of array items */
  maxCount?: number;
  /** Maximum value for numbers/dates or maximum length for strings */
  max?: number | Date | (() => number | Date);
  /** Minimum number of array items */
  minCount?: number;
  /** Minimum value for numbers/dates or minimum length for strings */
  min?: number | Date | (() => number | Date);
  /** Regular expression(s) for string validation */
  regEx?: RegExp | RegExp[];
  /** Skip regex validation for empty strings */
  skipRegExCheckForEmptyStrings?: boolean;
  /** Whether to trim string values during cleaning */
  trim?: boolean;
}

interface SchemaKeyDefinitionWithOneType extends SchemaKeyDefinitionBase {
  type: SupportedTypes;
}

Usage Examples:

import SimpleSchema from "simpl-schema";

// Shorthand definitions
const shorthandSchema = new SimpleSchema({
  name: String,           // String type
  age: Number,           // Number type
  isActive: Boolean,     // Boolean type
  tags: [String],        // Array of strings
  profile: Object        // Object type
});

// Longhand definitions with constraints
const detailedSchema = new SimpleSchema({
  name: {
    type: String,
    min: 1,
    max: 100,
    label: "Full Name",
    trim: true
  },
  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: 120,
    optional: true
  },
  tags: {
    type: Array,
    minCount: 0,
    maxCount: 10
  },
  'tags.$': {
    type: String,
    min: 1,
    max: 50
  }
});

// Mixed shorthand and longhand
const mixedSchema = new SimpleSchema({
  title: String,         // Shorthand
  description: {         // Longhand
    type: String,
    max: 1000,
    optional: true
  },
  priority: [String]     // Shorthand array
});

Supported Types

All JavaScript constructor types plus special SimpleSchema types.

type SupportedTypes = 
  | ArrayConstructor      // Array
  | BooleanConstructor    // Boolean  
  | DateConstructor       // Date
  | NumberConstructor     // Number
  | StringConstructor     // String
  | ObjectConstructor     // Object
  | '___Any___'           // Any type (SimpleSchema.Any)
  | typeof SimpleSchema.Integer  // Integer numbers only
  | SimpleSchema         // Nested schema
  | AnyClass            // Any class constructor
  | RegExp;             // Regular expression

// Special type constants
static Any: '___Any___';           // Allows any type
static Integer: 'SimpleSchema.Integer';  // Integer numbers only

Schema Extension

Extend existing schemas with additional fields or override existing field definitions.

/**
 * Creates a new schema by extending this schema with additional fields
 * @param schema - Schema or definition to extend with
 * @returns New SimpleSchema instance with combined definitions
 */
extend(schema: SimpleSchema | PartialSchemaDefinitionWithShorthand): SimpleSchema;

Usage Examples:

const baseSchema = new SimpleSchema({
  name: String,
  email: String
});

const extendedSchema = baseSchema.extend({
  age: Number,
  phone: {
    type: String,
    optional: true
  }
});

// Override existing fields
const modifiedSchema = baseSchema.extend({
  email: {
    type: String,
    regEx: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
    label: "Email Address"
  }
});

Schema Cloning

Create an exact copy of a schema for modification without affecting the original.

/**
 * Creates a deep copy of the schema
 * @returns New SimpleSchema instance with same definition
 */
clone(): SimpleSchema;

Schema Filtering

Create new schemas with only specified fields or excluding specified fields.

/**
 * Creates a new schema with only the specified fields
 * @param fields - Field names to include
 * @returns New SimpleSchema with only specified fields
 */
pick(...fields: string[]): SimpleSchema;

/**
 * Creates a new schema excluding the specified fields
 * @param fields - Field names to exclude
 * @returns New SimpleSchema without specified fields
 */
omit(...fields: string[]): SimpleSchema;

Usage Examples:

const fullSchema = new SimpleSchema({
  name: String,
  email: String,
  age: Number,
  phone: String,
  address: String
});

// Create schema with only specific fields
const contactSchema = fullSchema.pick('name', 'email', 'phone');

// Create schema excluding specific fields
const publicSchema = fullSchema.omit('age', 'address');

Schema Groups and Union Types

Create union types that allow multiple type options for a single field.

/**
 * Creates a schema group representing a union of multiple types
 * @param definitions - Array of type definitions to allow
 * @returns SimpleSchemaGroup instance
 */
static oneOf(...definitions): SimpleSchemaGroup;

class SimpleSchemaGroup {
  /** Array of type definitions in this group */
  definitions: SchemaKeyDefinitionWithOneType[];
  /** First type in the definitions (getter) */
  singleType: SupportedTypes;
  
  /** Creates a copy of the schema group */
  clone(): SimpleSchemaGroup;
  /** Extends this group with definitions from another group */
  extend(otherGroup: SimpleSchemaGroup): void;
}

Usage Examples:

const userSchema = new SimpleSchema({
  name: String,
  identifier: SimpleSchema.oneOf(String, Number), // Can be string or number
  contact: SimpleSchema.oneOf(
    { type: String, regEx: SimpleSchema.RegEx.Email },  // Email
    { type: String, regEx: /^\+?[1-9]\d{1,14}$/ }      // Phone
  )
});

Nested Schemas and Subschemas

Use SimpleSchema instances as types for nested object validation.

// Use SimpleSchema instance as a type
const addressSchema = new SimpleSchema({
  street: String,
  city: String,
  state: String,
  zipCode: String
});

const userSchema = new SimpleSchema({
  name: String,
  address: addressSchema,     // Nested schema
  workAddress: {              // Optional nested schema
    type: addressSchema,
    optional: true
  }
});

Function-Based Properties

Define dynamic field properties using functions for conditional validation.

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

// Properties that can be functions
interface DynamicProperties {
  allowedValues?: AllowedValues | (() => AllowedValues);
  exclusiveMax?: boolean | (() => boolean);  
  exclusiveMin?: boolean | (() => boolean);
  label?: string | ((this: FunctionOptionContext) => string);
  max?: number | Date | (() => number | Date);
  maxCount?: number | (() => number);
  min?: number | Date | (() => number | Date);
  minCount?: number | (() => number);
  optional?: boolean | (() => boolean);
  regEx?: RegExp | RegExp[] | (() => RegExp | RegExp[]);
  skipRegExCheckForEmptyStrings?: boolean | (() => boolean);
}

Usage Examples:

const conditionalSchema = new SimpleSchema({
  userType: {
    type: String,
    allowedValues: ['admin', 'user', 'guest']
  },
  permissions: {
    type: Array,
    minCount: function() {
      return this.field('userType').value === 'admin' ? 1 : 0;
    }
  },
  'permissions.$': String
});

Install with Tessl CLI

npx tessl i tessl/npm-simpl-schema

docs

data-cleaning.md

index.md

schema-definition.md

schema-introspection.md

utility-functions.md

validation-context.md

validation.md

tile.json