1.0.0 • Published 8 months ago

@compiledbox/ts-schema-validator v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

TS Schema Validator

TS Schema Validator is a lightweight, open-source library designed for robust runtime data validation in TypeScript applications. It bridges the gap between static type checks and dynamic data verification, ensuring that external inputs (such as API responses or user inputs) match the expected schema.

This approach provides a secure layer for validating data, reducing runtime errors, and maintaining consistency across client-server interactions. The library leverages an intuitive DSL that mirrors TypeScript types, allowing developers to build comprehensive validation schemas with ease.

Features

  • Schema Definition: Define validation schemas using a simple DSL mirroring TypeScript types.
  • Runtime Validation: Validate external data against your defined schema.
  • Detailed Errors: Returns precise error messages that include the data path, aiding in debugging.
  • Type-Safe: Fully typed validators.

Installation

npm install @compiledbox/ts-schema-validator

Usages

import { object, string, number, validate } from '@compiledbox/ts-schema-validator';

const userSchema = object({
  name: string(),
  age: number()
});

const result = validate(userSchema, { name: 'Alice', age: 30 });
if (result.success) {
  console.log('Valid data:', result.value);
} else {
  console.error('Validation errors:', result.errors);
}

Complex Usages

// complex-usage-user-profile.ts

import { validate, object, string, number, boolean, array, optional } from '@compiledbox/ts-schema-validator';

// Define schema for Address
const addressSchema = object({
  street: string(),
  city: string(),
  zipCode: number(),
});

// Define schema for a Product in an Order
const productSchema = object({
  productId: string(),
  productName: string(),
  price: number(),
});

// Define schema for an Order, which includes an array of Products and an optional discount field
const orderSchema = object({
  orderId: string(),
  products: array(productSchema),
  discount: optional(number()),
  isExpressDelivery: boolean(),
});

// Define the main User Profile schema, which includes a nested address object and an array of orders.
const userProfileSchema = object({
  userId: string(),
  name: string(),
  email: string(),
  address: addressSchema,
  orders: array(orderSchema),
});

// Example API response data (can be from a REST API or similar)
const apiResponse = {
  userId: 'user-001',
  name: 'Alice Johnson',
  email: 'alice@example.com',
  address: {
    street: '456 Elm Street',
    city: 'Metropolis',
    zipCode: 12345,
  },
  orders: [
    {
      orderId: 'order-1001',
      products: [
        { productId: 'prod-1', productName: 'Laptop', price: 1200 },
        { productId: 'prod-2', productName: 'Mouse', price: 25 },
      ],
      discount: 10,
      isExpressDelivery: false,
    },
    {
      orderId: 'order-1002',
      products: [
        { productId: 'prod-3', productName: 'Monitor', price: 300 },
      ],
      // 'discount' is optional here and not provided
      isExpressDelivery: true,
    },
  ],
};

// Validate the API response
const result = validate(userProfileSchema, apiResponse);

if (result.success) {
  console.log('API response is valid:', result.value);
} else {
  console.error('Validation errors:', result.errors);
}

API

Validators

  • string(): Validates string values.
  • number(): Validates number values.
  • boolean(): Validates boolean values.
  • array(validator): Validates arrays using a provided element validator.
  • object(schema): Validates objects where schema is an object mapping keys to validators.
  • optional(validator): Allows a value to be undefined or a valid type.

validate

A helper function to run validation:

validate(validator, data);

Contributing

Contributions are welcome! Please:

  • Fork the repository.
  • Create a branch for your changes.
  • Write tests for any new features.
  • Submit a pull request with detailed changes.

License

This project is licensed under the MIT License