All files / src/api validation.js

17.93% Statements 33/184
100% Branches 0/0
0% Functions 0/5
17.93% Lines 33/184

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 2001x 1x 1x 1x       1x 1x 1x 1x 1x 1x                                                                                           1x 1x 1x 1x 1x 1x 1x                                                                                                                                                 1x 1x 1x 1x 1x                           1x 1x 1x 1x 1x                           1x 1x 1x 1x 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 fieldErrors = validateField(fieldSchema, fieldValue, field);
          errors.push(...fieldErrors);
        }
      }
    }
  }
  
  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 {Array} Validation errors
 */
function validateField(schema, value, fieldName) {
  const errors = [];
  
  // Type validation
  if (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') {
    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') {
    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 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
};