All files / apps/host/src/services/notification notificationApi.ts

89.7% Statements 61/68
70.58% Branches 24/34
100% Functions 12/12
89.7% Lines 61/68

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                                                3x 3x 3x           2x 2x   2x       2x         2x 2x 2x                       6x     6x 1x       5x 1x       4x               4x 4x 4x 4x 4x       3x 3x   1x   1x                             1x   4x 4x       4x       3x 3x             2x         2x 2x 2x 1x 1x   1x 1x 1x       2x                         3x 3x 3x   3x                                 1x   1x                                                   2x   2x 2x 2x       1x   1x   1x                           1x   2x                 11x 11x 11x             2x 2x    
import DeviceInfo from 'react-native-device-info';
import { Platform } from 'react-native';
 
import { REQUEST_POLICY, runRequestEffect } from '@repo/services/effectRequest';
 
import { getPlatform } from '@repo/utils/platform';
 
import { ENDPOINTS } from '@/constants/apis';
 
import { https } from '@/services/mainHttpClient';
import { sentryService } from '@/services/sentryService';
 
export interface RegisterNotificationTokenParams {
  token: string;
  deviceName: string;
  deviceId: string;
  platform: 'ios' | 'android';
}
 
export interface RegisterNotificationTokenResponse {
  [key: string]: unknown;
}
 
// Track last registered token to prevent duplicates
let lastRegisteredToken: string | null = null;
let registrationPromise: Promise<RegisterNotificationTokenResponse> | null = null;
let registrationTokenInFlight: string | null = null;
 
/**
 * Extract HTTP status code from error message
 */
function extractStatusFromError(error: unknown): number | null {
  Eif (typeof error === 'object' && error !== null) {
    const httpLike = error as { status?: unknown; statusCode?: unknown };
 
    Iif (typeof httpLike.statusCode === 'number') {
      return httpLike.statusCode;
    }
 
    Iif (typeof httpLike.status === 'number') {
      return httpLike.status;
    }
  }
 
  Eif (error instanceof Error) {
    const match = error.message.match(/status (\d+)/);
    return match ? parseInt(match[1], 10) : null;
  }
  return null;
}
 
/**
 * Register FCM token with backend
 * Prevents duplicate registrations of the same token
 */
export async function registerNotificationToken(
  params: RegisterNotificationTokenParams,
): Promise<RegisterNotificationTokenResponse> {
  const { token } = params;
 
  // Prevent duplicate registration of the same token
  if (lastRegisteredToken === token) {
    return {} as RegisterNotificationTokenResponse;
  }
 
  // If a registration is already in-flight for the same token, reuse it
  if (registrationPromise && registrationTokenInFlight === token) {
    return registrationPromise;
  }
 
  // If a different token is registering, wait for it to finish to avoid overlap
  Iif (registrationPromise) {
    try {
      await registrationPromise;
    } catch {
      // Ignore errors from previous attempt; we'll try again for the new token
    }
  }
 
  registrationTokenInFlight = token;
  registrationPromise = (async () => {
    try {
      const response = await runRequestEffect(
        () => https.post<RegisterNotificationTokenResponse>(ENDPOINTS.NOTIFICATIONS, params),
        REQUEST_POLICY.IDEMPOTENT_WRITE,
      );
 
      lastRegisteredToken = token;
      return response.data;
    } catch (error: unknown) {
      const statusCode = extractStatusFromError(error) || 'unknown';
 
      sentryService.captureException(error, {
        tags: {
          component: 'notification',
          action: 'register_token',
          status_code: String(statusCode),
        },
        extra: {
          endpoint: ENDPOINTS.NOTIFICATIONS,
          payload: {
            ...params,
            token: `${params.token.substring(0, 20)}...`,
          },
        },
      });
 
      throw error;
    } finally {
      registrationPromise = null;
      registrationTokenInFlight = null;
    }
  })();
 
  return registrationPromise;
}
 
// Cache device ID to avoid async calls
let cachedDeviceId: string | null = null;
let deviceIdPromise: Promise<string> | null = null;
 
/**
 * Initialize device ID asynchronously
 * Call this once at app startup to cache the real device ID
 */
export async function initializeDeviceId(): Promise<void> {
  Iif (deviceIdPromise) {
    await deviceIdPromise;
    return;
  }
 
  deviceIdPromise = (async () => {
    try {
      const id = await DeviceInfo.getUniqueId();
      cachedDeviceId = id;
      return id;
    } catch {
      const fallbackId = `${getPlatform()}-${Platform.Version}`;
      cachedDeviceId = fallbackId;
      return fallbackId;
    }
  })();
 
  await deviceIdPromise;
}
 
/**
 * Get device information for token registration
 * Uses react-native-device-info for unique device ID
 * Note: Call initializeDeviceId() at app startup for best results
 */
export function getDeviceInfo(): {
  deviceName: string;
  deviceId: string;
  platform: 'ios' | 'android';
} {
  const platform = getPlatform();
  const deviceId = cachedDeviceId || `${platform}-${Platform.Version}`;
  const deviceName = DeviceInfo.getDeviceNameSync() || `${platform} Device`;
 
  return {
    deviceName,
    deviceId,
    platform,
  };
}
 
/**
 * Create notification token registration payload
 */
export function createTokenRegistrationPayload(
  token: string,
  options?: {
    deviceName?: string;
    deviceId?: string;
  },
): RegisterNotificationTokenParams {
  const deviceInfo = getDeviceInfo();
 
  return {
    token,
    deviceName: options?.deviceName || deviceInfo.deviceName,
    deviceId: options?.deviceId || deviceInfo.deviceId,
    platform: deviceInfo.platform,
  };
}
 
export interface DeleteNotificationTokenParams {
  deviceId: string;
}
 
export interface DeleteNotificationTokenResponse {
  [key: string]: unknown;
}
 
/**
 * Delete notification token from backend
 * Used when user logs out
 * @param userId - User ID (Firebase UID)
 * @param deviceId - Device ID from getDeviceInfo()
 */
export async function deleteNotificationToken(
  userId: string,
  deviceId: string,
): Promise<DeleteNotificationTokenResponse> {
  const endpoint = `${ENDPOINTS.NOTIFICATIONS}/${userId}`;
 
  try {
    const response = await runRequestEffect(
      () => https.patch<DeleteNotificationTokenResponse>(endpoint, { deviceId }),
      REQUEST_POLICY.WRITE,
    );
 
    return response.data;
  } catch (error: unknown) {
    const statusCode = extractStatusFromError(error) || 'unknown';
 
    sentryService.captureException(error, {
      tags: {
        component: 'notification',
        action: 'delete_token',
        status_code: String(statusCode),
      },
      extra: {
        endpoint,
        userId,
        deviceId,
      },
    });
 
    // Don't throw error - allow logout to proceed even if token deletion fails
    return {} as DeleteNotificationTokenResponse;
  } finally {
    resetTokenRegistrationCache();
  }
}
 
/**
 * Reset the last registered token cache
 * Useful when user logs out and logs back in
 */
export function resetTokenRegistrationCache(): void {
  lastRegisteredToken = null;
  registrationPromise = null;
  registrationTokenInFlight = null;
}
 
/**
 * Reset device ID cache for testing
 */
export function resetDeviceIdCache(): void {
  cachedDeviceId = null;
  deviceIdPromise = null;
}