Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Use persisted store for definition version keys #2090

Merged
merged 1 commit into from
Jul 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions native/app/App.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import * as SplashScreen from "expo-splash-screen";

import MainDrawer from "@/app/UI/MainDrawer.tsx";
import Login from "@/app/UI/Login.tsx";
Expand All @@ -16,6 +17,7 @@ function App() {
if (!stateHydrated) {
return null;
}
SplashScreen.hideAsync();

return (
<RootStack.Navigator>
Expand Down
24 changes: 12 additions & 12 deletions native/app/Root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ if (Platform.OS !== "web") {

const startupTime = performance.now();
useGGStore.getState().setAppStartupTime(startupTime);
useGGStore.getState().initAuthentication();
useGGStore.getState().initDefinitions();

enableFreeze(true);

Expand Down Expand Up @@ -69,6 +67,7 @@ async function getBungieDefinitions() {
}

async function init() {
useGGStore.getState().initAuthentication();
getCustomItemDefinition();
getBungieDefinitions();
}
Expand Down Expand Up @@ -98,6 +97,14 @@ const navigationContainerTheme: Theme = {
dark: false,
};

function refreshIfNeeded() {
const lastRefresh = useGGStore.getState().lastRefreshTime;
const now = performance.now();
if (now - lastRefresh > 35000) {
getFullProfile();
}
}

// If the them is not set a white background keeps showing during screen rotation
function Root() {
"use memo";
Expand Down Expand Up @@ -127,6 +134,7 @@ function Root() {
const navigationRef = useRef<NavigationContainerRef<ReactNavigation.RootParamList>>(null);
const { width } = useWindowDimensions();
const SCREEN_WIDTH = width;
const stateHydrated = useGGStore((state) => state.stateHydrated);

useEffect(() => {
if (SCREEN_WIDTH) {
Expand All @@ -135,7 +143,7 @@ function Root() {
}, [SCREEN_WIDTH]);

useEffect(() => {
if (authenticated === "NO-AUTHENTICATION") {
if (authenticated === "NO-AUTHENTICATION" && stateHydrated) {
if (navigationRef.current) {
navigationRef.current.navigate("Login");
} else {
Expand All @@ -148,15 +156,7 @@ function Root() {

return () => clearInterval(intervalId);
}
}, [authenticated, itemsDefinitionReady, bungieDefinitionsReady]);

function refreshIfNeeded() {
const lastRefresh = useGGStore.getState().lastRefreshTime;
const now = performance.now();
if (now - lastRefresh > 35000) {
getFullProfile();
}
}
}, [authenticated, itemsDefinitionReady, bungieDefinitionsReady, stateHydrated]);

return (
<GestureHandlerRootView>
Expand Down
79 changes: 5 additions & 74 deletions native/app/store/DefinitionsSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { Platform } from "react-native";
import { parse, safeParse, string } from "valibot";
import type { StateCreator } from "zustand";
import Toast from "react-native-toast-message";
import * as SplashScreen from "expo-splash-screen";
import { deepEqual } from "fast-equals";

import {
Expand Down Expand Up @@ -44,7 +43,7 @@ import {
setDestinyInventoryBucketDefinition,
} from "@/app/store/Definitions.ts";
import type { IStore } from "@/app/store/GGStore.ts";
import { DatabaseStore, Store, type AsyncStorageKey, type StorageKey } from "@/app/store/Types.ts";
import { DatabaseStore, type AsyncStorageKey, type StorageKey } from "@/app/store/Types.ts";
import { getCustomItemDefinition } from "@/app/utilities/Helpers.ts";
import {
ItemResponseSchema,
Expand Down Expand Up @@ -72,7 +71,6 @@ export interface DefinitionsSlice {
inventorySectionWidth: number;
itemDefinitionVersion: string;
bungieDefinitionVersions: string;
initDefinitions: () => Promise<void>;
loadCustomDefinitions: (uniqueKey: string | null) => Promise<void>;
loadBungieDefinitions: (bungieManifest: BungieManifest | null) => Promise<void>;
showSnackBar: (message: string) => void;
Expand All @@ -88,23 +86,6 @@ export const createDefinitionsSlice: StateCreator<IStore, [], [], DefinitionsSli
inventorySectionWidth: 0,
itemDefinitionVersion: "",
bungieDefinitionVersions: "",
initDefinitions: async () => {
try {
const loadedDefinitionVersion = await loadItemDefinitionVersion();
set({ itemDefinitionVersion: loadedDefinitionVersion });
} catch (e) {
console.log("No saved itemDefinition version", e);
}

try {
const bungieDefinitionVersion = await loadBungieDefinitionsVersion();
set({ bungieDefinitionVersions: bungieDefinitionVersion });
} catch (e) {
console.log("No saved bungieDefinition version", e);
} finally {
SplashScreen.hideAsync();
}
},
loadCustomDefinitions: async (uniqueKey) => {
const storedVersion = get().itemDefinitionVersion;
if (storedVersion === "") {
Expand Down Expand Up @@ -162,9 +143,7 @@ export const createDefinitionsSlice: StateCreator<IStore, [], [], DefinitionsSli
},
setInventorySectionWidth: (inventorySectionWidth) => set({ inventorySectionWidth }),
clearCache: () => {
saveItemDefinitionVersion("");
saveBungieDefinitionsVersion("");
set({ itemsDefinitionReady: false });
set({ itemDefinitionVersion: "", bungieDefinitionVersions: "", itemsDefinitionReady: false });
},
});

Expand All @@ -184,7 +163,7 @@ async function downloadAndStoreItemDefinition(set: DefinitionsSliceSetter): Prom
const downloadedDefinition = await getCustomItemDefinition();
const itemDefinition = parse(ItemResponseSchema, downloadedDefinition);
const versionKey = itemDefinition.id;
await saveItemDefinitionVersion(versionKey);
set({ itemDefinitionVersion: versionKey });
await setData(itemDefinition as unknown as JSON, "ITEM_DEFINITION", "setupItemDefinition()");
return set(parseAndSet(itemDefinition));
} catch (e) {
Expand Down Expand Up @@ -288,9 +267,7 @@ async function downloadAndStoreBungieDefinitions(
} else {
throw new Error("No DestinyInventoryBucketDefinition");
}

await saveBungieDefinitionsVersion(versionKey);
set({ bungieDefinitionsReady: true });
set({ bungieDefinitionVersions: versionKey, bungieDefinitionsReady: true });
} catch (e) {
console.error("Failed to download and save bungieDefinition", e);
if (failCount < 3) {
Expand Down Expand Up @@ -325,7 +302,7 @@ async function loadLocalBungieDefinitions(set: DefinitionsSliceSetter): Promise<
set({ bungieDefinitionsReady: true });
} catch (e) {
console.error("Failed to load bungieDefinition version", e);
saveBungieDefinitionsVersion("");
set({ bungieDefinitionVersions: "", bungieDefinitionsReady: false });
// TODO: Should error. Show something to the user that lets them restart the app. In the sense of running init again.
}
}
Expand Down Expand Up @@ -555,52 +532,6 @@ export async function setAsyncStorage(key: AsyncStorageKey, data: string): Promi
}
}

export async function loadItemDefinitionVersion(): Promise<string> {
const version = await AsyncStorage.getItem(Store._item_definition);
if (version) {
const validatedVersion = safeParse(string(), version);

if (validatedVersion.success) {
return validatedVersion.output;
}
throw new Error("Validation failed");
}
throw new Error("No saved itemDefinition version found");
}

export async function saveItemDefinitionVersion(version: string): Promise<void> {
try {
await AsyncStorage.setItem(Store._item_definition, version);
console.log("saved", version);
} catch (error: unknown) {
console.error("Failed to save itemDefinition version", error);
throw new Error("Failed to save itemDefinition version");
}
}

export async function loadBungieDefinitionsVersion(): Promise<string> {
const version = await AsyncStorage.getItem(Store._bungie_definitions);
if (version) {
const validatedVersion = safeParse(string(), version);

if (validatedVersion.success) {
return validatedVersion.output;
}
throw new Error("Validation failed");
}
throw new Error("No saved bungieDefinitions version found");
}

export async function saveBungieDefinitionsVersion(version: string): Promise<void> {
try {
await AsyncStorage.setItem(Store._bungie_definitions, version);
console.log("saved bungie", version);
} catch (error: unknown) {
console.error("Failed to save itemDefinition version", error);
throw new Error("Failed to save itemDefinition version");
}
}

async function getBungieDefinition(definitionUrl: string): Promise<JSON> {
const requestOptions: RequestInit = {
method: "GET",
Expand Down
2 changes: 2 additions & 0 deletions native/app/store/GGStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ export const useGGStore = create<IStore>()(
armorSort: state.armorSort,
showBottomSheetPreference: state.showBottomSheetPreference,
showNextBottomSheet: state.showNextBottomSheet,
itemDefinitionVersion: state.itemDefinitionVersion,
bungieDefinitionVersions: state.bungieDefinitionVersions,
}),
onRehydrateStorage: () => {
return (state, error) => {
Expand Down