All files / varjoliitokauppa/lib validation.ts

77.41% Statements 24/31
75% Branches 24/32
100% Functions 7/7
77.41% Lines 24/31

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        2x 2x         3x 3x     3x     3x       3x 3x     3x     3x       2x 2x     2x 1x   1x       1x 1x     1x       1x 1x     1x       11x 1x   10x    
// Validation utilities for API routes
 
export class ValidationError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'ValidationError';
  }
}
 
export function validatePrice(price: unknown): number {
  const parsed = typeof price === 'number' ? price : parseFloat(String(price));
  Iif (isNaN(parsed)) {
    throw new ValidationError('Price must be a valid number');
  }
  Iif (parsed < 0) {
    throw new ValidationError('Price cannot be negative');
  }
  return parsed;
}
 
export function validateStock(stock: unknown): number {
  const parsed = typeof stock === 'number' ? stock : parseInt(String(stock));
  Iif (isNaN(parsed)) {
    throw new ValidationError('Stock must be a valid number');
  }
  Iif (parsed < 0) {
    throw new ValidationError('Stock cannot be negative');
  }
  return parsed;
}
 
export function validateRating(rating: unknown): number {
  const parsed = typeof rating === 'number' ? rating : parseInt(String(rating));
  Iif (isNaN(parsed)) {
    throw new ValidationError('Rating must be a valid number');
  }
  if (parsed < 1 || parsed > 5) {
    throw new ValidationError('Rating must be between 1 and 5');
  }
  return parsed;
}
 
export function validateOrderStatus(status: unknown): string {
  const validStatuses = ['pending', 'processing', 'shipped', 'delivered', 'cancelled'];
  Iif (typeof status !== 'string' || !validStatuses.includes(status)) {
    throw new ValidationError(`Order status must be one of: ${validStatuses.join(', ')}`);
  }
  return status;
}
 
export function validateReviewStatus(status: unknown): string {
  const validStatuses = ['pending', 'approved', 'rejected'];
  Iif (typeof status !== 'string' || !validStatuses.includes(status)) {
    throw new ValidationError(`Review status must be one of: ${validStatuses.join(', ')}`);
  }
  return status;
}
 
export function validateRequired(value: unknown, fieldName: string): string {
  if (typeof value !== 'string' || value.trim() === '') {
    throw new ValidationError(`${fieldName} is required`);
  }
  return value;
}