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

100% Statements 19/19
90% Branches 9/10
100% Functions 3/3
100% Lines 15/15

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                        4x 3x     1x 1x 1x                   3x 6x 6x 4x 1x 1x     2x 1x 1x     1x    
import type { FirebaseMessagingTypes } from '@react-native-firebase/messaging';
import { getToken } from '@react-native-firebase/messaging';
 
import { isIOS } from '@repo/utils/platform';
 
// Fetch token with iOS retry logic
export async function fetchFCMToken(
  messaging: FirebaseMessagingTypes.Module,
  onTokenReceived: (token: string) => void,
  maxRetries = 10,
  initialDelay = 1000,
): Promise<string | null> {
  if (isIOS()) {
    return await fetchFCMTokenWithRetry(messaging, onTokenReceived, maxRetries, initialDelay);
  }
 
  const token = await getToken(messaging);
  Eif (token) onTokenReceived(token);
  return token;
}
 
// iOS specific retry logic
async function fetchFCMTokenWithRetry(
  messaging: FirebaseMessagingTypes.Module,
  onTokenReceived: (token: string) => void,
  maxRetries: number,
  initialDelay: number,
): Promise<string | null> {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const token = await getToken(messaging);
      if (token) {
        onTokenReceived(token);
        return token;
      }
    } catch (error) {
      if (attempt === maxRetries - 1) throw error;
      const delay = initialDelay * Math.pow(2, attempt);
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
  return null;
}