Skip to content

Commit

Permalink
add enum for storage keys
Browse files Browse the repository at this point in the history
resolves nasa#2
  • Loading branch information
12ya committed May 6, 2024
1 parent 8cfd3b5 commit edc83ef
Show file tree
Hide file tree
Showing 17 changed files with 85 additions and 59 deletions.
6 changes: 3 additions & 3 deletions app/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -146,14 +146,14 @@ function App(props: AppProps) {
useEffect(() => {
;(async () => {
try {
const locale = await storage.load("locale")
const locale = await storage.load(storage.KEYS.LOCALE)
if (locale) setLocale(locale as string)
else {
const prevSystemLocale = await storage.load("prevSystemLocale")
const prevSystemLocale = await storage.load(storage.KEYS.PREV_SYSTEM_LOCALE)
if (prevSystemLocale && prevSystemLocale !== i18n.locale) updateLocationAddresses()
}

await storage.save("prevSystemLocale", i18n.locale)
await storage.save(storage.KEYS.PREV_SYSTEM_LOCALE, i18n.locale)
setIsLocaleLoaded(true)
} catch {
setIsLocaleLoaded(true)
Expand Down
4 changes: 2 additions & 2 deletions app/models/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const RootStoreActions = (self) => ({
const isCurrentLocation = locationCopy.title === self.currentLocation?.title
const isSelectedLocation = locationCopy.title === self.selectedLocation?.title
const locationSightings = locationCopy?.sightings ? [...locationCopy?.sightings] : []
const isNotifyAll = Boolean(yield storage.load("upcoming"))
const isNotifyAll = Boolean(yield storage.load(storage.KEYS.UPCOMING))
const dataToSave = data.sightings.map((item: ISSSighting) => {
const sighting = locationSightings.find(
({ date }) => date.substring(0, 17) === item.date.substring(0, 17),
Expand Down Expand Up @@ -302,7 +302,7 @@ const RootStoreActions = (self) => ({
})

if (ok) {
const isNotifyAll = Boolean(yield storage.load("upcoming"))
const isNotifyAll = Boolean(yield storage.load(storage.KEYS.UPCOMING))
const locationSightings = valueCopy.sightings ? [...valueCopy.sightings] : []
const dataToSave = data.sightings.map((item: ISSSighting) => {
const sighting = locationSightings.find(
Expand Down
5 changes: 3 additions & 2 deletions app/models/helpers/setupRootStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import * as storage from "../../utils/storage"
/**
* The key we'll be saving our state as within async storage.
*/
const ROOT_STATE_STORAGE_KEY = "root-v1"

/**
* Setup the root state.
Expand All @@ -40,7 +39,9 @@ export async function setupRootStore(rootStore: RootStore) {
if (_disposer) _disposer()

// track changes & save to AsyncStorage
_disposer = onSnapshot(rootStore, (snapshot) => storage.save(ROOT_STATE_STORAGE_KEY, snapshot))
_disposer = onSnapshot(rootStore, (snapshot) =>
storage.save(storage.KEYS.ROOT_STATE_STORAGE_KEY, snapshot),
)

const unsubscribe = () => {
_disposer()
Expand Down
5 changes: 4 additions & 1 deletion app/navigators/AppNavigator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,10 @@ const AppStack = observer(function AppStack() {
const prevAppState = useRef<string>()

useEffect(() => {
Promise.all([storage.load("isSettingsCompleted"), notifications.hasInitialNotification()])
Promise.all([
storage.load(storage.KEYS.IS_SETTINGS_COMPLETED),
notifications.hasInitialNotification(),
])
.then(([isSettingsCompleted, hasInitialNotification]) => {
if (isSettingsCompleted) skipOnboarding()
if (hasInitialNotification) {
Expand Down
2 changes: 1 addition & 1 deletion app/navigators/navigationUtilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ function navigationRestoredDefaultState(persistNavigation: PersistNavigationConf
/**
* Custom hook for persisting navigation state.
*/
export function useNavigationPersistence(persistenceKey: string) {
export function useNavigationPersistence(persistenceKey: storage.KEYS) {
const [initialNavigationState, setInitialNavigationState] = useState<NavigationState>()
const isMounted = useIsMounted()

Expand Down
4 changes: 2 additions & 2 deletions app/screens/MainScreen/HomeScreen/HomeScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ export const HomeScreen = observer(function HomeScreen() {
}, [currentSighting, startCountdown, timeDiff])

const getCoach = async () => {
const coachCompleted = await storage.load("coachCompleted")
const coachCompleted = await storage.load(storage.KEYS.COACH_COMPLETED)
if (coachCompleted) requestCloseModal("coach")
else requestOpenModal("coach")
}
Expand Down Expand Up @@ -224,7 +224,7 @@ export const HomeScreen = observer(function HomeScreen() {

const handleSetCoachCompleted = async () => {
requestCloseModal("coach")
await storage.save("coachCompleted", true)
await storage.save(storage.KEYS.COACH_COMPLETED, true)
}

const handleChangeLocation = useCallback(
Expand Down
4 changes: 2 additions & 2 deletions app/screens/MainScreen/HomeScreen/Sightings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ export function Sightings({
}

const getCoach = async () => {
setSightingsCoachVisible(!(await storage.load("sightingsCoachVisible")))
setSightingsCoachVisible(!(await storage.load(storage.KEYS.SIGHTINGS_COACH_VISIBLE)))
}

useEffect(() => {
Expand All @@ -203,7 +203,7 @@ export function Sightings({

const handleSetSightingsCoachVisible = async () => {
setSightingsCoachVisible(false)
await storage.save("sightingsCoachVisible", true)
await storage.save(storage.KEYS.SIGHTINGS_COACH_VISIBLE, true)
}

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,20 +87,20 @@ export const NotificationSettingsScreen = observer(function NotificationSettings
}, [currentLocation, savedLocations])

const loadSettings = async () => {
const start = (await storage.load("muteFrom")) as string
const end = (await storage.load("muteUntil")) as string
const notifyBefore = await storage.load("notifyBefore")
const start = (await storage.load(storage.KEYS.MUTE_FROM)) as string
const end = (await storage.load(storage.KEYS.MUTE_UNTIL)) as string
const notifyBefore = await storage.load(storage.KEYS.NOTIFY_BEFORE)

setSettings({
iisVisible: await storage.load("iisVisible"),
upcoming: await storage.load("upcoming"),
inApp: await storage.load("inApp"),
iisVisible: await storage.load(storage.KEYS.I_IS_VISIBLE),
upcoming: await storage.load(storage.KEYS.UPCOMING),
inApp: await storage.load(storage.KEYS.IN_APP),
notifyBefore: notifyBefore || 15,
privacy: await storage.load("privacy"),
privacy: await storage.load(storage.KEYS.PRIVACY),
muteFrom: start ? new Date(start) : new Date(),
muteUntil: end ? new Date(end) : new Date(),
})
!notifyBefore && (await storage.save("notifyBefore", 15))
!notifyBefore && (await storage.save(storage.KEYS.NOTIFY_BEFORE, 15))
}

useEffect(() => {
Expand Down Expand Up @@ -138,13 +138,13 @@ export const NotificationSettingsScreen = observer(function NotificationSettings
upcoming: !isNotifyAll,
})

storage.save("upcoming", !isNotifyAll).catch(console.error)
storage.save(storage.KEYS.UPCOMING, !isNotifyAll).catch(console.error)

setNotifications()
}, [currentLocation, selectedLocation, savedLocations, isNotifyAll, settings])

const handleChange = useCallback(
async (value, field: string) => {
async (value, field: storage.KEYS) => {
setSettings({
...settings,
[field]: value,
Expand Down Expand Up @@ -280,7 +280,7 @@ export const NotificationSettingsScreen = observer(function NotificationSettings
{ label: `30 ${translate("units.minute")}`, value: 30 },
{ label: `60 ${translate("units.minute")}`, value: 60 },
]}
onValueChange={(value) => handleChange(value, "notifyBefore")}
onValueChange={(value) => handleChange(value, storage.KEYS.NOTIFY_BEFORE)}
value={settings?.notifyBefore}
/>
</ExpandContainer>
Expand All @@ -292,7 +292,7 @@ export const NotificationSettingsScreen = observer(function NotificationSettings
accessibilityHint="toggle privacy notifications"
variant="switch"
value={settings?.privacy}
onValueChange={(value) => handleChange(value, "privacy")}
onValueChange={(value) => handleChange(value, storage.KEYS.PRIVACY)}
/>
</View>
<ExpandContainer
Expand Down Expand Up @@ -353,7 +353,7 @@ export const NotificationSettingsScreen = observer(function NotificationSettings
date={settings?.muteFrom}
onConfirm={(date) => {
setFrom(false)
handleChange(date, "muteFrom").catch(console.error)
handleChange(date, storage.KEYS.MUTE_FROM).catch(console.error)
}}
onCancel={() => setFrom(false)}
/>
Expand All @@ -363,7 +363,7 @@ export const NotificationSettingsScreen = observer(function NotificationSettings
date={settings?.muteUntil}
onConfirm={(date) => {
setUntil(false)
handleChange(date, "muteUntil").catch(console.error)
handleChange(date, storage.KEYS.MUTE_UNTIL).catch(console.error)
}}
onCancel={() => setUntil(false)}
/>
Expand Down
6 changes: 3 additions & 3 deletions app/screens/MainScreen/SettingsScreen/SettingsScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const SettingsScreen = observer(function SettingsScreen() {
navigation.navigate("SettingsScreens" as never, { screen } as never)

const onChangeLanguage = async ({ value }) => {
await storage.save("locale", value)
await storage.save(storage.KEYS.LOCALE, value)
setLocale(value as string)
setNotifications()
navigation.reset({
Expand All @@ -79,10 +79,10 @@ export const SettingsScreen = observer(function SettingsScreen() {
const handleTutorialClose = async (tutorial?: string) => {
setIsTutorialsModalVisible(false)
if (tutorial === "home") {
await storage.remove("coachCompleted")
await storage.remove(storage.KEYS.COACH_COMPLETED)
navigation.navigate("Home" as never)
} else if (tutorial === "ar") {
await storage.remove("arCoachCompleted")
await storage.remove(storage.KEYS.AR_COACH_COMPLETED)
navigation.navigate("ISSView" as never)
}
}
Expand Down
4 changes: 2 additions & 2 deletions app/screens/MainScreen/SkyViewScreen/ISSViewScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ export const ISSViewScreen = observer(function ISSNowScreen() {

useEffect(() => {
storage
.load("arCoachCompleted")
.load(storage.KEYS.AR_COACH_COMPLETED)
.then((completed) => setArCoachCompleted(Boolean(completed)))
.catch(() => setArCoachCompleted(true))
}, [])
Expand Down Expand Up @@ -642,7 +642,7 @@ export const ISSViewScreen = observer(function ISSNowScreen() {

const handleSetCoachCompleted = async () => {
requestCloseModal("arCoach")
await storage.save("arCoachCompleted", true)
await storage.save(storage.KEYS.AR_COACH_COMPLETED, true)
setArCoachCompleted(true)
}

Expand Down
4 changes: 2 additions & 2 deletions app/screens/OnboardingScreen/CompleteProfile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export const CompleteProfile = observer(function CompleteProfile() {
.logTutorialComplete()
.catch(() => null)
storage
.save("isSettingsCompleted", true)
.save(storage.KEYS.IS_SETTINGS_COMPLETED, true)
.then(() => skipOnboarding())
.catch((err) =>
Snackbar.show({
Expand Down Expand Up @@ -80,7 +80,7 @@ export const CompleteProfile = observer(function CompleteProfile() {

const handleNotificationsChange = async (notifications: boolean) => {
setNotifications(notifications)
await storage.save("upcoming", notifications)
await storage.save(storage.KEYS.UPCOMING, notifications)
}

const renderBody = useCallback(() => {
Expand Down
6 changes: 3 additions & 3 deletions app/screens/OnboardingScreen/SignupLocation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ export function SignupLocation({ value, onValueChange, onAction }: SignupLocatio
handleDetect().catch((e) => console.log(e))
} else {
storage
.load("isPrivacyAgree")
.load(storage.KEYS.IS_PRIVACY_AGREE)
.then((res) => {
if (res) handleDetect().catch((e) => console.log(e))
else setPrivacyModal(true)
Expand Down Expand Up @@ -325,15 +325,15 @@ export function SignupLocation({ value, onValueChange, onAction }: SignupLocatio
<PrivacyModal
onPressSkip={() => {
storage
.save("isPrivacyAgree", false)
.save(storage.KEYS.IS_PRIVACY_AGREE, false)
.then(() => {
setPrivacyModal(false)
})
.catch((e) => console.log(e))
}}
onPressAgree={() => {
storage
.save("isPrivacyAgree", true)
.save(storage.KEYS.IS_PRIVACY_AGREE, true)
.then(() => {
setPrivacyModal(false)
handleDetect().catch((e) => console.log(e))
Expand Down
4 changes: 2 additions & 2 deletions app/screens/OnboardingScreen/Splash.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export function Splash() {
const $topInset = useSafeAreaInsetsStyle(["top", "bottom"], "padding")

const generateUser = async () => {
let userId = (await storage.load("userId")) as string
let userId = (await storage.load(storage.KEYS.USER_ID)) as string
if (!userId) {
userId = getUserId()
await analytics()
Expand All @@ -42,7 +42,7 @@ export function Splash() {
await analytics()
.logTutorialBegin()
.catch(() => null)
await storage.save("userId", getUserId())
await storage.save(storage.KEYS.USER_ID, getUserId())
setTimeout(() => {
handleNavigate()
}, 3000)
Expand Down
4 changes: 2 additions & 2 deletions app/utils/geolocation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export const getCurrentLocation = async (

let prevLocation: LocationType = null
try {
prevLocation = JSON.parse((await storage.load("userCurrentLocation")) as string)
prevLocation = JSON.parse((await storage.load(storage.KEYS.USER_CURRENT_LOCATION)) as string)
} catch {}

if (coords) {
Expand All @@ -88,7 +88,7 @@ export const getCurrentLocation = async (
location: { lat: latitude, lng: longitude },
}

await storage.save("userCurrentLocation", JSON.stringify(result))
await storage.save(storage.KEYS.USER_CURRENT_LOCATION, JSON.stringify(result))
return result
}

Expand Down
8 changes: 4 additions & 4 deletions app/utils/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,10 @@ export async function hasInitialNotification() {
}

export async function setNotifications(locations: LocationType[]) {
const start = new Date((await storage.load("muteFrom")) as string)
const end = new Date((await storage.load("muteUntil")) as string)
const privacy = await storage.load("privacy")
const notifyBefore: number = (await storage.load("notifyBefore")) || 15
const start = new Date((await storage.load(storage.KEYS.MUTE_FROM)) as string)
const end = new Date((await storage.load(storage.KEYS.MUTE_UNTIL)) as string)
const privacy = await storage.load(storage.KEYS.PRIVACY)
const notifyBefore: number = (await storage.load(storage.KEYS.NOTIFY_BEFORE)) || 15

let notifications: { fireDate: Date; title: string; body: string }[] = []
for await (const location of locations) {
Expand Down
18 changes: 9 additions & 9 deletions app/utils/storage/__tests__/storage.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import AsyncStorage from "@react-native-async-storage/async-storage"
import { load, loadString, save, saveString, clear, remove } from "../storage"
import { load, loadString, save, saveString, clear, remove, KEYS } from "../storage"

// fixtures
const VALUE_OBJECT = { x: 1 }
Expand All @@ -9,28 +9,28 @@ beforeEach(() => (AsyncStorage.getItem as jest.Mock).mockReturnValue(Promise.res
afterEach(() => jest.clearAllMocks())

test("load", async () => {
const value = await load("something")
const value = await load(KEYS.SOMETHING)
expect(value).toEqual(JSON.parse(VALUE_STRING))
})

test("loadString", async () => {
const value = await loadString("something")
const value = await loadString(KEYS.SOMETHING)
expect(value).toEqual(VALUE_STRING)
})

test("save", async () => {
await save("something", VALUE_OBJECT)
expect(AsyncStorage.setItem).toHaveBeenCalledWith("something", VALUE_STRING)
await save(KEYS.SOMETHING, VALUE_OBJECT)
expect(AsyncStorage.setItem).toHaveBeenCalledWith(KEYS.SOMETHING, VALUE_STRING)
})

test("saveString", async () => {
await saveString("something", VALUE_STRING)
expect(AsyncStorage.setItem).toHaveBeenCalledWith("something", VALUE_STRING)
await saveString(KEYS.SOMETHING, VALUE_STRING)
expect(AsyncStorage.setItem).toHaveBeenCalledWith(KEYS.SOMETHING, VALUE_STRING)
})

test("remove", async () => {
await remove("something")
expect(AsyncStorage.removeItem).toHaveBeenCalledWith("something")
await remove(KEYS.SOMETHING)
expect(AsyncStorage.removeItem).toHaveBeenCalledWith(KEYS.SOMETHING)
})

test("clear", async () => {
Expand Down
Loading

0 comments on commit edc83ef

Please sign in to comment.