All files / api/src validation.js

75.8% Statements 47/62
80.45% Branches 70/87
50% Functions 4/8
75.8% Lines 47/62

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213                            16x         16x 14x 3x       3x       11x 7x 14x 7x                 11x 5x 10x 9x 9x 9x 4x             13x                           31x     31x                     31x 31x 3x       28x 1x       27x 1x       26x 1x               31x 12x 3x           12x 1x           12x 3x               31x 8x 1x           8x 1x             31x                 3x 2x 2x   2x 1x     1x                                                                                                
/**
 * API Validation for Coherent.js
 * @fileoverview Schema-based validation utilities
 */
 
import { ValidationError } from './errors.js';
 
/**
 * Validate data against a schema
 * @param {Object} schema - JSON Schema
 * @param {any} data - Data to validate
 * @returns {Object} Validation result
 */
function validateAgainstSchema(schema, data) {
  const errors = [];
 
  // Simple validation implementation
  // In a real implementation, this would use a proper JSON Schema validator
 
  if (schema.type === 'object') {
    if (typeof data !== 'object' || data === null || Array.isArray(data)) {
      errors.push({
        field: '',
        message: `Expected object, got ${typeof data}`
      });
      return { valid: false, errors };
    }
 
    // Check required fields
    if (schema.required && Array.isArray(schema.required)) {
      for (const field of schema.required) {
        if (!(field in data)) {
          errors.push({
            field,
            message: `Required field '${field}' is missing`
          });
        }
      }
    }
 
    // Validate properties
    if (schema.properties) {
      for (const [field, fieldSchema] of Object.entries(schema.properties)) {
        if (field in data) {
          const fieldValue = data[field];
          const fieldResult = validateField(fieldSchema, fieldValue, field);
          if (!fieldResult.valid) {
            errors.push(...fieldResult.errors);
          }
        }
      }
    }
  }
 
  return {
    valid: errors.length === 0,
    errors
  };
}
 
/**
 * Validate a single field
 * @param {Object} schema - Field schema
 * @param {any} value - Field value
 * @param {string} fieldName - Field name
 * @returns {Object} Validation result with valid and errors properties
 */
function validateField(schema, value, fieldName) {
  const errors = [];
 
  // Handle null/undefined values
  Iif (value === null || value === undefined) {
    if (schema.type && schema.type !== 'null') {
      errors.push({
        field: fieldName,
        message: `Expected ${schema.type}, got ${value === null ? 'null' : 'undefined'}`
      });
    }
    return { valid: errors.length === 0, errors };
  }
 
  // Type validation
  Eif (schema.type) {
    if (schema.type === 'string' && typeof value !== 'string') {
      errors.push({
        field: fieldName,
        message: `Expected string, got ${typeof value}`
      });
    } else if (schema.type === 'number' && typeof value !== 'number') {
      errors.push({
        field: fieldName,
        message: `Expected number, got ${typeof value}`
      });
    } else if (schema.type === 'boolean' && typeof value !== 'boolean') {
      errors.push({
        field: fieldName,
        message: `Expected boolean, got ${typeof value}`
      });
    } else if (schema.type === 'array' && !Array.isArray(value)) {
      errors.push({
        field: fieldName,
        message: `Expected array, got ${typeof value}`
      });
    }
  }
 
  // String-specific validations
  if (schema.type === 'string' && typeof value === 'string') {
    if (schema.minLength && value.length < schema.minLength) {
      errors.push({
        field: fieldName,
        message: `String must be at least ${schema.minLength} characters`
      });
    }
 
    if (schema.maxLength && value.length > schema.maxLength) {
      errors.push({
        field: fieldName,
        message: `String must be at most ${schema.maxLength} characters`
      });
    }
 
    if (schema.format === 'email' && !/^[^@]+@[^@]+\.[^@]+$/.test(value)) {
      errors.push({
        field: fieldName,
        message: 'Invalid email format'
      });
    }
  }
 
  // Number-specific validations
  if (schema.type === 'number' && typeof value === 'number') {
    if (schema.minimum !== undefined && value < schema.minimum) {
      errors.push({
        field: fieldName,
        message: `Number must be at least ${schema.minimum}`
      });
    }
 
    if (schema.maximum !== undefined && value > schema.maximum) {
      errors.push({
        field: fieldName,
        message: `Number must be at most ${schema.maximum}`
      });
    }
  }
 
  return { valid: errors.length === 0, errors };
}
 
/**
 * Create validation middleware
 * @param {Object} schema - JSON Schema for validation
 * @returns {Function} Middleware function
 */
function withValidation(schema) {
  return (req, res, next) => {
    const data = req.body || {};
    const result = validateAgainstSchema(schema, data);
 
    if (!result.valid) {
      throw new ValidationError(result.errors);
    }
 
    next();
  };
}
 
/**
 * Validate query parameters
 * @param {Object} schema - JSON Schema for query parameters
 * @returns {Function} Middleware function
 */
function withQueryValidation(schema) {
  return (req, res, next) => {
    const data = req.query || {};
    const result = validateAgainstSchema(schema, data);
 
    if (!result.valid) {
      throw new ValidationError(result.errors);
    }
 
    next();
  };
}
 
/**
 * Validate path parameters
 * @param {Object} schema - JSON Schema for path parameters
 * @returns {Function} Middleware function
 */
function withParamsValidation(schema) {
  return (req, res, next) => {
    const data = req.params || {};
    const result = validateAgainstSchema(schema, data);
 
    if (!result.valid) {
      throw new ValidationError(result.errors);
    }
 
    next();
  };
}
 
// Export validation utilities
export {
  validateAgainstSchema,
  validateField,
  withValidation,
  withQueryValidation,
  withParamsValidation
};