All files / services offlineAwareApi.ts

0% Statements 0/91
0% Branches 0/38
0% Functions 0/67
0% Lines 0/55

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 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
/**
 * Offline-Aware API Wrapper
 *
 * Wraps API calls with offline detection and graceful error handling.
 * Provides consistent error messages and retry logic for network failures.
 */
 
import { api } from './api';
import { isOnline, retryWithBackoff, DEFAULT_RETRY_CONFIG, RetryConfig } from '@/utils/networkStatus';
import type { ApiResponse, ApiError } from '@/types';
 
/**
 * Network-related error codes
 */
export const NETWORK_ERROR_CODES = {
  OFFLINE: 'NETWORK_OFFLINE',
  TIMEOUT: 'NETWORK_TIMEOUT',
  UNREACHABLE: 'NETWORK_UNREACHABLE',
} as const;
 
/**
 * User-friendly error messages for network issues
 */
export const NETWORK_ERROR_MESSAGES = {
  OFFLINE: 'No internet connection. Please check your network and try again.',
  TIMEOUT: 'Request timed out. Please try again.',
  UNREACHABLE: 'Unable to reach the server. Please try again later.',
  GENERIC: 'Network error occurred. Please check your connection.',
} as const;
 
/**
 * Check if error is network-related
 */
export function isNetworkError(error: ApiError): boolean {
  if (!error) return false;
 
  const code = error.code?.toUpperCase() || '';
  const message = error.message?.toLowerCase() || '';
 
  return (
    code === 'NETWORK_ERROR' ||
    code === 'NETWORK_OFFLINE' ||
    code === 'NETWORK_TIMEOUT' ||
    code === 'NETWORK_UNREACHABLE' ||
    message.includes('network') ||
    message.includes('offline') ||
    message.includes('connection') ||
    message.includes('timeout') ||
    message.includes('fetch')
  );
}
 
/**
 * Get user-friendly error message for network errors
 */
export function getNetworkErrorMessage(error: ApiError): string {
  if (!isNetworkError(error)) {
    return error.message || 'An error occurred';
  }
 
  const code = error.code?.toUpperCase();
  if (code === 'NETWORK_OFFLINE') return NETWORK_ERROR_MESSAGES.OFFLINE;
  if (code === 'NETWORK_TIMEOUT') return NETWORK_ERROR_MESSAGES.TIMEOUT;
  if (code === 'NETWORK_UNREACHABLE') return NETWORK_ERROR_MESSAGES.UNREACHABLE;
 
  return NETWORK_ERROR_MESSAGES.GENERIC;
}
 
/**
 * Wrap an API call with offline detection
 *
 * @param apiCall - The API function to call
 * @param options - Configuration options
 * @returns Promise with API response
 *
 * @example
 * const response = await withOfflineCheck(() => api.getAllBeneficiaries());
 * if (!response.ok) {
 *   Alert.alert('Error', getNetworkErrorMessage(response.error));
 * }
 */
export async function withOfflineCheck<T>(
  apiCall: () => Promise<ApiResponse<T>>,
  options: {
    retry?: boolean;
    retryConfig?: RetryConfig;
    offlineMessage?: string;
  } = {}
): Promise<ApiResponse<T>> {
  // Check if online before attempting request
  const online = await isOnline();
 
  if (!online) {
    return {
      ok: false,
      error: {
        message: options.offlineMessage || NETWORK_ERROR_MESSAGES.OFFLINE,
        code: NETWORK_ERROR_CODES.OFFLINE,
      },
    };
  }
 
  try {
    // Execute API call with optional retry
    if (options.retry) {
      return await retryWithBackoff(apiCall, options.retryConfig || DEFAULT_RETRY_CONFIG);
    }
 
    return await apiCall();
  } catch (error) {
    // Convert exception to ApiResponse format
    const apiError: ApiError = {
      message: error instanceof Error ? error.message : 'Unknown error',
      code: 'NETWORK_ERROR',
    };
 
    return {
      ok: false,
      error: apiError,
    };
  }
}
 
/**
 * Offline-aware API service
 * Wraps the main API service with network detection
 *
 * Use this instead of direct `api` imports for better offline handling
 */
export const offlineAwareApi = {
  // ==================== Authentication ====================
 
  async checkEmail(email: string) {
    return withOfflineCheck(() => api.checkEmail(email), {
      retry: true,
      offlineMessage: 'Cannot verify email while offline',
    });
  },
 
  async requestOTP(email: string) {
    return withOfflineCheck(() => api.requestOTP(email), {
      retry: true,
      offlineMessage: 'Cannot send verification code while offline',
    });
  },
 
  async verifyOTP(email: string, code: string) {
    return withOfflineCheck(() => api.verifyOTP(email, code), {
      retry: true,
      offlineMessage: 'Cannot verify code while offline',
    });
  },
 
  async getProfile() {
    return withOfflineCheck(() => api.getProfile(), {
      retry: true,
    });
  },
 
  async updateProfile(updates: Parameters<typeof api.updateProfile>[0]) {
    return withOfflineCheck(() => api.updateProfile(updates), {
      offlineMessage: 'Cannot update profile while offline',
    });
  },
 
  async updateProfileAvatar(imageUri: string | null) {
    return withOfflineCheck(() => api.updateProfileAvatar(imageUri), {
      offlineMessage: 'Cannot upload avatar while offline',
    });
  },
 
  // ==================== Beneficiaries ====================
 
  async getAllBeneficiaries() {
    return withOfflineCheck(() => api.getAllBeneficiaries(), {
      retry: true,
    });
  },
 
  async getWellNuoBeneficiary(id: number) {
    return withOfflineCheck(() => api.getWellNuoBeneficiary(id), {
      retry: true,
    });
  },
 
  async createBeneficiary(data: Parameters<typeof api.createBeneficiary>[0]) {
    return withOfflineCheck(() => api.createBeneficiary(data), {
      offlineMessage: 'Cannot add beneficiary while offline',
    });
  },
 
  async updateWellNuoBeneficiary(id: number, updates: Parameters<typeof api.updateWellNuoBeneficiary>[1]) {
    return withOfflineCheck(() => api.updateWellNuoBeneficiary(id, updates), {
      offlineMessage: 'Cannot update beneficiary while offline',
    });
  },
 
  async updateBeneficiaryAvatar(id: number, imageUri: string | null) {
    return withOfflineCheck(() => api.updateBeneficiaryAvatar(id, imageUri), {
      offlineMessage: 'Cannot upload avatar while offline',
    });
  },
 
  async updateBeneficiaryCustomName(id: number, customName: string | null) {
    return withOfflineCheck(() => api.updateBeneficiaryCustomName(id, customName), {
      offlineMessage: 'Cannot update name while offline',
    });
  },
 
  async deleteBeneficiary(id: number) {
    return withOfflineCheck(() => api.deleteBeneficiary(id), {
      offlineMessage: 'Cannot remove beneficiary while offline',
    });
  },
 
  // ==================== Devices / Sensors ====================
 
  async getDevicesForBeneficiary(beneficiaryId: string) {
    return withOfflineCheck(() => api.getDevicesForBeneficiary(beneficiaryId), {
      retry: true,
    });
  },
 
  async attachDeviceToBeneficiary(beneficiaryId: string, wellId: number, deviceMac: string) {
    return withOfflineCheck(() => api.attachDeviceToBeneficiary(beneficiaryId, wellId, deviceMac), {
      offlineMessage: 'Cannot attach sensor while offline',
    });
  },
 
  async updateDeviceMetadata(deviceId: string, updates: Parameters<typeof api.updateDeviceMetadata>[1]) {
    return withOfflineCheck(() => api.updateDeviceMetadata(deviceId, updates), {
      offlineMessage: 'Cannot update sensor settings while offline',
    });
  },
 
  async detachDeviceFromBeneficiary(beneficiaryId: string, deviceId: string) {
    return withOfflineCheck(() => api.detachDeviceFromBeneficiary(beneficiaryId, deviceId), {
      offlineMessage: 'Cannot remove sensor while offline',
    });
  },
 
  async getSensorHealthHistory(deviceId: string, timeRange: '24h' | '7d' | '30d' = '24h') {
    return withOfflineCheck(() => api.getSensorHealthHistory(deviceId, timeRange), {
      retry: true,
    });
  },
 
  // ==================== Subscriptions ====================
 
  async cancelSubscription(beneficiaryId: number) {
    return withOfflineCheck(() => api.cancelSubscription(beneficiaryId), {
      offlineMessage: 'Cannot cancel subscription while offline',
    });
  },
 
  async reactivateSubscription(beneficiaryId: number) {
    return withOfflineCheck(() => api.reactivateSubscription(beneficiaryId), {
      offlineMessage: 'Cannot reactivate subscription while offline',
    });
  },
 
  async getTransactionHistory(beneficiaryId: number, limit = 10) {
    return withOfflineCheck(() => api.getTransactionHistory(beneficiaryId, limit), {
      retry: true,
    });
  },
 
  // ==================== Invitations ====================
 
  async sendInvitation(params: Parameters<typeof api.sendInvitation>[0]) {
    return withOfflineCheck(() => api.sendInvitation(params), {
      offlineMessage: 'Cannot send invitation while offline',
    });
  },
 
  async getInvitations(beneficiaryId: string) {
    return withOfflineCheck(() => api.getInvitations(beneficiaryId), {
      retry: true,
    });
  },
 
  async deleteInvitation(invitationId: string) {
    return withOfflineCheck(() => api.deleteInvitation(invitationId), {
      offlineMessage: 'Cannot delete invitation while offline',
    });
  },
 
  async updateInvitation(invitationId: string, role: 'caretaker' | 'guardian') {
    return withOfflineCheck(() => api.updateInvitation(invitationId, role), {
      offlineMessage: 'Cannot update invitation while offline',
    });
  },
 
  async acceptInvitation(code: string) {
    return withOfflineCheck(() => api.acceptInvitation(code), {
      offlineMessage: 'Cannot accept invitation while offline',
    });
  },
 
  // ==================== Notifications ====================
 
  async getNotificationSettings() {
    return withOfflineCheck(() => api.getNotificationSettings(), {
      retry: true,
    });
  },
 
  async updateNotificationSettings(settings: Parameters<typeof api.updateNotificationSettings>[0]) {
    return withOfflineCheck(() => api.updateNotificationSettings(settings), {
      offlineMessage: 'Cannot update notification settings while offline',
    });
  },
 
  async getNotificationHistory(options?: Parameters<typeof api.getNotificationHistory>[0]) {
    return withOfflineCheck(() => api.getNotificationHistory(options), {
      retry: true,
    });
  },
 
  // ==================== AI Chat (Legacy API) ====================
 
  async sendMessage(question: string, deploymentId: string) {
    return withOfflineCheck(() => api.sendMessage(question, deploymentId), {
      offlineMessage: 'Cannot send message while offline',
    });
  },
 
  // ==================== Equipment Activation ====================
 
  async activateBeneficiary(beneficiaryId: number, serialNumber: string) {
    return withOfflineCheck(() => api.activateBeneficiary(beneficiaryId, serialNumber), {
      offlineMessage: 'Cannot activate equipment while offline',
    });
  },
 
  async updateBeneficiaryEquipmentStatus(
    id: number,
    status: 'none' | 'ordered' | 'shipped' | 'delivered'
  ) {
    return withOfflineCheck(() => api.updateBeneficiaryEquipmentStatus(id, status), {
      offlineMessage: 'Cannot update equipment status while offline',
    });
  },
};
 
/**
 * Export utility functions
 */
export { isNetworkError as isOfflineError, getNetworkErrorMessage as getOfflineErrorMessage };