import AsyncStorage from "@react-native-async-storage/async-storage"; import type { IStorageService } from "./IStorageService"; import type { WidgetSamplerLog } from "../../domain"; import { STORAGE_KEY } from "../../constants/Constants"; export class AsyncStorageService implements IStorageService { private key: string; constructor(storageId: string) { this.key = `${STORAGE_KEY}_${storageId}`; } async read(key?: string): Promise { const storageKey = key || this.key; try { const json = await AsyncStorage.getItem(storageKey); return json ? (JSON.parse(json) as WidgetSamplerLog) : this.getDefaultValue(); } catch (error) { console.error("Error reading from AsyncStorage:", error); return this.getDefaultValue(); } } async write(key: string, data: WidgetSamplerLog): Promise; async write(data: WidgetSamplerLog): Promise; async write(keyOrData: string | WidgetSamplerLog, data?: WidgetSamplerLog): Promise { try { let storageKey: string; let storageData: WidgetSamplerLog; if (typeof keyOrData === "string") { storageKey = keyOrData; storageData = data!; } else { storageKey = this.key; storageData = keyOrData; } const json = JSON.stringify(storageData); await AsyncStorage.setItem(storageKey, json); } catch (error) { console.error("Error writing to AsyncStorage:", error); throw error; } } async delete(key?: string): Promise { const storageKey = key || this.key; try { await AsyncStorage.removeItem(storageKey); } catch (error) { console.error("Error deleting from AsyncStorage:", error); throw error; } } async exists(key?: string): Promise { const storageKey = key || this.key; try { const value = await AsyncStorage.getItem(storageKey); return value !== null; } catch (error) { console.error("Error checking existence in AsyncStorage:", error); return false; } } private getDefaultValue(): WidgetSamplerLog { return { attempts: 0, answeredTransactionIds: [], }; } }