All files / src/lib/pwa background-sync.ts

0% Statements 0/243
100% Branches 0/0
0% Functions 0/1
0% Lines 0/243

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 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
/**
 * Background Sync Service
 *
 * Handles syncing pending actions when the device comes back online.
 * Uses the Background Sync API when available, with fallback to manual sync.
 */

import { clientLogger } from '@/lib/logging/clientLogger';
import {
  getPendingActions,
  removePendingAction,
  incrementRetryCount,
  clearFailedActions,
  type PendingAction,
  type PendingActionType,
} from './offline-storage';

// Sync configuration
const SYNC_CONFIG = {
  maxRetries: 5,
  retryDelay: 1000, // Base delay in ms (exponential backoff)
  syncTag: 'elite-events-sync',
} as const;

/**
 * Process a single pending action
 */
async function processAction(action: PendingAction): Promise<boolean> {
  const { type, payload } = action;

  try {
    switch (type) {
      case 'ADD_TO_CART': {
        const response = await fetch('/api/cart', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        });
        return response.ok;
      }

      case 'UPDATE_CART': {
        const cartPayload = payload as { id: string; quantity: number };
        const response = await fetch(`/api/cart/${cartPayload.id}`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ quantity: cartPayload.quantity }),
        });
        return response.ok;
      }

      case 'REMOVE_FROM_CART': {
        const removePayload = payload as { id: string };
        const response = await fetch(`/api/cart/${removePayload.id}`, {
          method: 'DELETE',
        });
        return response.ok;
      }

      case 'ADD_TO_WISHLIST': {
        const response = await fetch('/api/wishlist', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        });
        return response.ok;
      }

      case 'REMOVE_FROM_WISHLIST': {
        const wishlistPayload = payload as { id: string };
        const response = await fetch(`/api/wishlist/${wishlistPayload.id}`, {
          method: 'DELETE',
        });
        return response.ok;
      }

      case 'SUBMIT_REVIEW': {
        const response = await fetch('/api/reviews', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        });
        return response.ok;
      }

      case 'UPDATE_PROFILE': {
        const response = await fetch('/api/user/profile', {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        });
        return response.ok;
      }

      default: {
        clientLogger.warn('Unknown action type', {
          category: 'SYSTEM',
          type,
        });
        return false;
      }
    }
  } catch (error) {
    clientLogger.error(`Failed to process action ${type}`, error instanceof Error ? error : undefined, {
      category: 'SYSTEM',
      actionType: type,
    });
    return false;
  }
}

/**
 * Sync all pending actions
 */
export async function syncPendingActions(): Promise<{
  synced: number;
  failed: number;
}> {
  const actions = await getPendingActions();
  let synced = 0;
  let failed = 0;

  for (const action of actions) {
    const success = await processAction(action);

    if (success && action.id !== undefined) {
      await removePendingAction(action.id);
      synced++;
    } else if (action.id !== undefined) {
      await incrementRetryCount(action.id);
      failed++;
    }
  }

  // Clean up actions that have exceeded max retries
  await clearFailedActions(SYNC_CONFIG.maxRetries);

  return { synced, failed };
}

/**
 * Register for background sync if supported
 */
export async function registerBackgroundSync(): Promise<boolean> {
  if (
    typeof navigator === 'undefined' ||
    !('serviceWorker' in navigator) ||
    !('sync' in ServiceWorkerRegistration.prototype)
  ) {
    return false;
  }

  try {
    const registration = await navigator.serviceWorker.ready;
    // @ts-expect-error - sync is not in the TypeScript types
    await registration.sync.register(SYNC_CONFIG.syncTag);
    return true;
  } catch (error) {
    clientLogger.warn('Background sync registration failed', {
      category: 'SYSTEM',
      error: error instanceof Error ? error.message : String(error),
    });
    return false;
  }
}

/**
 * Handle online event - sync pending actions
 */
function handleOnline(): void {
  // Add small delay to ensure connection is stable
  setTimeout(async () => {
    const { failed } = await syncPendingActions();
    if (failed > 0) {
      clientLogger.warn(`Failed to sync ${failed} actions`, {
        category: 'SYSTEM',
        failedCount: failed,
      });
    }
  }, 1000);
}

/**
 * Initialize background sync listeners
 */
export function initBackgroundSync(): () => void {
  if (typeof window === 'undefined') {
    return () => {};
  }

  // Listen for online events
  window.addEventListener('online', handleOnline);

  // Register for background sync
  registerBackgroundSync();

  // If already online, sync any pending actions
  if (navigator.onLine) {
    syncPendingActions();
  }

  // Return cleanup function
  return () => {
    window.removeEventListener('online', handleOnline);
  };
}

/**
 * Get count of pending actions
 */
export async function getPendingActionCount(): Promise<number> {
  const actions = await getPendingActions();
  return actions.length;
}

/**
 * Check if there are pending actions to sync
 */
export async function hasPendingActions(): Promise<boolean> {
  const count = await getPendingActionCount();
  return count > 0;
}

/**
 * Queue an action with automatic sync attempt if online
 */
export async function queueAndSync(
  type: PendingActionType,
  payload: unknown
): Promise<void> {
  // Import dynamically to avoid circular dependency
  const { queueAction } = await import('./offline-storage');

  await queueAction(type, payload);

  // If online, try to sync immediately
  if (typeof navigator !== 'undefined' && navigator.onLine) {
    await syncPendingActions();
  } else {
    // Register for background sync
    await registerBackgroundSync();
  }
}