All files / src/lib/cart cart-storage.ts

98.69% Statements 151/153
93.54% Branches 29/31
100% Functions 14/14
98.69% Lines 151/153

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 1541x 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 20x 20x 20x 20x 1x 1x 1x 1x 1x 5x 3x 5x 2x 2x 5x 1x 1x 1x 1x 1x 5x 3x 5x 2x 2x 5x 1x 1x 1x 1x 1x 5x 3x 5x 2x 2x 5x 1x 1x 1x 1x 1x 9x 4x 9x 5x 5x 9x 1x 1x 1x 1x 3x 3x 1x 1x 3x 3x 1x 1x 1x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 7x 3x 3x 3x 3x 7x 4x 4x 4x 7x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 3x 3x 3x  
import { CartItem } from '@/redux/features/cartSlice';
import {
  setCartCookie,
  getCartCookie,
  deleteCartCookie,
  getAnonymousSessionId } from './cart-cookie';
import { logger } from '@/lib/logging';
 
export type CartStorageType = 'cookie' | 'database';
 
export interface CartStorageOptions {
  type: CartStorageType;
  userId?: number;
  deviceId?: string;
}
 
/**
 * Abstraction layer for cart persistence
 * Handles both cookie-based (anonymous) and database-based (authenticated) storage
 */
export class CartStorage {
  private type: CartStorageType;
  private userId?: number;
  private deviceId?: string;
 
  constructor(options: CartStorageOptions) {
    this.type = options.type;
    this.userId = options.userId;
    this.deviceId = options.deviceId;
  }
 
  /**
   * Save cart items to storage
   */
  async save(items: CartItem[]): Promise<boolean> {
    if (this.type === 'cookie') {
      return this.saveToCookie(items);
    } else {
      return this.saveToDatabase(items);
    }
  }
 
  /**
   * Load cart items from storage
   */
  async load(): Promise<CartItem[]> {
    if (this.type === 'cookie') {
      return this.loadFromCookie();
    } else {
      return this.loadFromDatabase();
    }
  }
 
  /**
   * Clear cart from storage
   */
  async clear(): Promise<void> {
    if (this.type === 'cookie') {
      deleteCartCookie();
    } else {
      await this.clearDatabase();
    }
  }
 
  /**
   * Get session identifier
   */
  getSessionId(): string {
    if (this.type === 'cookie') {
      return getAnonymousSessionId();
    } else {
      return `user_${this.userId}_${this.deviceId || 'default'}`;
    }
  }
 
  // Private methods
 
  private saveToCookie(items: CartItem[]): boolean {
    return setCartCookie(items);
  }
 
  private loadFromCookie(): CartItem[] {
    return getCartCookie() || [];
  }
 
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  private async saveToDatabase(_items: CartItem[]): Promise<boolean> {
    // This will be implemented when integrating with Redux async thunks
    // For now, we'll use the API endpoints
    logger.warn('Database save not yet implemented - use Redux thunks', { category: 'CART' });
    return false;
  }
 
  private async loadFromDatabase(): Promise<CartItem[]> {
    // This will be implemented when integrating with Redux async thunks
    // For now, we'll use the API endpoints
    logger.warn('Database load not yet implemented - use Redux thunks', { category: 'CART' });
    return [];
  }
 
  private async clearDatabase(): Promise<void> {
    // This will be implemented when integrating with Redux async thunks
    logger.warn('Database clear not yet implemented - use Redux thunks', { category: 'CART' });
  }
 
  /**
   * Static factory method to create appropriate storage instance
   */
  static create(isAuthenticated: boolean, userId?: number, deviceId?: string): CartStorage {
    if (isAuthenticated && userId) {
      return new CartStorage({
        type: 'database',
        userId,
        deviceId});
    } else {
      return new CartStorage({
        type: 'cookie'});
    }
  }
 
  /**
   * Check if storage is available
   */
  static isStorageAvailable(): boolean {
    if (typeof window === 'undefined') return false;
 
    try {
      // Test cookie availability
      const testKey = '__storage_test__';
      document.cookie = `${testKey}=1; path=/; max-age=0`;
      const cookieEnabled = document.cookie.includes(testKey);
      document.cookie = `${testKey}=; path=/; max-age=-1`;
      return cookieEnabled;
    } catch {
      return false;
    }
  }
}
 
/**
 * Helper function to determine current storage type
 */
export function getCurrentStorageType(isAuthenticated: boolean): CartStorageType {
  return isAuthenticated ? 'database' : 'cookie';
}
 
/**
 * Helper function to migrate from cookie to database
 * Returns the items from cookie that need to be merged
 */
export function getCartItemsForMigration(): CartItem[] | null {
  return getCartCookie();
}