All files / src/lib/validation index.ts

90.1% Statements 164/182
80% Branches 8/10
75% Functions 6/8
90.1% Lines 164/182

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 1831x 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 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 3x 3x 3x 4x 4x 4x 4x 4x 3x 3x 3x     6x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 1x 1x 1x 1x           1x 1x 1x 1x                       1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 1x 1x 1x 1x 3x 3x 3x 3x  
/**
 * Centralized Validation Module
 *
 * Provides type-safe validation helpers for data validation.
 * This is the single entry point for all validation in the application.
 *
 * @example
 * ```ts
 * // Import schemas
 * import { emailSchema, loginSchema, paginationSchema } from '@/lib/validation';
 *
 * // Import middleware
 * import { withValidation } from '@/lib/validation';
 *
 * // Import error utilities
 * import { formatZodError, ValidationError } from '@/lib/validation';
 * ```
 */
 
import { z, ZodError, type ZodSchema } from 'zod';
 
// Re-export all schemas (common and domain-specific)
export * from './schemas';
 
// Re-export domain-specific schemas
export * from './schemas/auth';
export * from './schemas/user';
export * from './schemas/product';
export * from './schemas/order';
 
// Re-export error types and utilities
export * from './errors';
 
// Note: The following modules use NextRequest which is not available in Jest tests.
// Import them directly when needed in API routes:
// import { withValidation } from '@/lib/validation/middleware'
// import { validateRequestBody } from '@/lib/validation/api-validation'
 
// ============================================================================
// TYPES
// ============================================================================
 
/**
 * Simple validation result (for non-API contexts)
 */
export type SimpleValidationResult<T> =
  | { success: true; data: T }
  | { success: false; errors: Record<string, string[]> };
 
/**
 * Formatted validation error details
 */
export interface ValidationErrorDetail {
  field: string;
  message: string;
}
 
// ============================================================================
// SIMPLE VALIDATION
// ============================================================================
 
/**
 * Validate data against a Zod schema
 *
 * @example
 * ```ts
 * const result = validateData(formData, MySchema);
 * if (!result.success) {
 *   console.error(result.errors);
 *   return;
 * }
 * const data = result.data;
 * ```
 */
export function validateData<T>(
  data: unknown,
  schema: ZodSchema<T>
): SimpleValidationResult<T> {
  try {
    const validatedData = schema.parse(data);
    return { success: true, data: validatedData };
  } catch (error) {
    if (error instanceof ZodError) {
      const errors: Record<string, string[]> = {};
      error.issues.forEach((issue) => {
        const path = issue.path.join('.') || '_root';
        if (!errors[path]) {
          errors[path] = [];
        }
        errors[path].push(issue.message);
      });
      return { success: false, errors };
    }
    return { success: false, errors: { _root: ['Validation failed'] } };
  }
}
 
/**
 * Safe parse with type inference (wrapper around Zod's safeParse)
 * Returns { success: true, data: T } or { success: false, error: ZodError }
 */
export function safeParse<T>(
  data: unknown,
  schema: ZodSchema<T>
): { success: true; data: T } | { success: false; error: ZodError } {
  return schema.safeParse(data);
}
 
/**
 * Validate route parameters (from URL path)
 * Works without NextRequest - just pass the params object
 *
 * @example
 * ```ts
 * const result = validateRouteParams({ id: params.id }, z.object({ id: idSchema }));
 * if (!result.success) {
 *   // Handle error
 * }
 * const { id } = result.data;
 * ```
 */
export function validateRouteParams<T>(
  params: Record<string, string | string[] | undefined>,
  schema: ZodSchema<T>
): SimpleValidationResult<T> {
  return validateData(params, schema);
}
 
// ============================================================================
// ERROR HANDLING
// ============================================================================
 
/**
 * Check if an error is a Zod validation error
 */
export function isValidationError(error: unknown): error is ZodError {
  return error instanceof ZodError;
}
 
/**
 * Format a ZodError into a list of field-message pairs
 */
export function formatValidationErrors(error: ZodError): ValidationErrorDetail[] {
  return error.issues.map((issue) => ({
    field: issue.path.join('.') || '_root',
    message: issue.message}));
}
 
/**
 * Get validation error messages as a simple object
 */
export function getValidationErrors(error: ZodError): Record<string, string[]> {
  const errors: Record<string, string[]> = {};
  error.issues.forEach((issue) => {
    const path = issue.path.join('.') || '_root';
    if (!errors[path]) {
      errors[path] = [];
    }
    errors[path].push(issue.message);
  });
  return errors;
}
 
// ============================================================================
// UTILITY SCHEMAS
// ============================================================================
 
/**
 * Create an ID param schema for route handlers
 */
export function createIdParamSchema(paramName: string = 'id') {
  return z.object({
    [paramName]: z.coerce.number().int().positive(`Invalid ${paramName}`)});
}
 
/**
 * Create a slug param schema for route handlers
 */
export function createSlugParamSchema(paramName: string = 'slug') {
  return z.object({
    [paramName]: z.string().min(1, `${paramName} is required`)});
}