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

96.29% Statements 26/27
90% Branches 9/10
100% Functions 5/5
100% Lines 24/24

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        3x 3x           3x 2x 2x   1x             1x       3x       5x 1x     4x 4x 3x 3x 3x   1x           1x         3x 3x   3x 3x         1x 1x                     6x    
import AsyncStorage from '@react-native-async-storage/async-storage';
 
import { sentryService } from '@/services/sentryService';
 
const NOTIFICATION_PREFERENCE_STORAGE_KEY = '@host/notifications-enabled';
const DEFAULT_NOTIFICATION_PREFERENCE = true;
type StoredNotificationPreference = 'true' | 'false';
 
let notificationPreferenceCache: boolean | undefined;
 
function parseStoredNotificationPreference(value: string | null): boolean {
  if (value === null) return DEFAULT_NOTIFICATION_PREFERENCE;
  Iif (value === 'true') return true;
  if (value === 'false') return false;
 
  sentryService.captureException(new Error('Invalid notification preference value'), {
    tags: {
      component: 'notification',
      action: 'parse_preference',
    },
    extra: { value },
  });
  return DEFAULT_NOTIFICATION_PREFERENCE;
}
 
function toStoredNotificationPreference(value: boolean): StoredNotificationPreference {
  return value ? 'true' : 'false';
}
 
export async function getNotificationPreference(): Promise<boolean> {
  if (notificationPreferenceCache !== undefined) {
    return notificationPreferenceCache;
  }
 
  try {
    const storedPreference = await AsyncStorage.getItem(NOTIFICATION_PREFERENCE_STORAGE_KEY);
    const parsedPreference = parseStoredNotificationPreference(storedPreference);
    notificationPreferenceCache = parsedPreference;
    return parsedPreference;
  } catch (error) {
    sentryService.captureException(error, {
      tags: {
        component: 'notification',
        action: 'get_preference',
      },
    });
    return DEFAULT_NOTIFICATION_PREFERENCE;
  }
}
 
export async function setNotificationPreference(isEnabled: boolean): Promise<void> {
  const previousCacheValue = notificationPreferenceCache;
  notificationPreferenceCache = isEnabled;
 
  try {
    await AsyncStorage.setItem(
      NOTIFICATION_PREFERENCE_STORAGE_KEY,
      toStoredNotificationPreference(isEnabled),
    );
  } catch (error) {
    notificationPreferenceCache = previousCacheValue;
    sentryService.captureException(error, {
      tags: {
        component: 'notification',
        action: 'set_preference',
      },
      extra: { isEnabled },
    });
  }
}
 
export function resetNotificationPreferenceCache(): void {
  notificationPreferenceCache = undefined;
}