mirror of
https://github.com/ManInDark/HabitTrove.git
synced 2026-01-20 22:24:28 +01:00
refresh stale data (#156)
This commit is contained in:
@@ -29,6 +29,9 @@ import { signInSchema } from '@/lib/zod';
|
||||
import { auth } from '@/auth';
|
||||
import _ from 'lodash';
|
||||
import { getCurrentUser, getCurrentUserId } from '@/lib/server-helpers'
|
||||
import stableStringify from 'json-stable-stringify';
|
||||
import { prepareDataForHashing, generateCryptoHash } from '@/lib/utils';
|
||||
|
||||
|
||||
import { PermissionError } from '@/lib/exceptions'
|
||||
|
||||
@@ -123,6 +126,33 @@ async function saveData<T>(type: DataType, data: T): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the server's global freshness token based on all core data files.
|
||||
* This is an expensive operation as it reads all data files.
|
||||
*/
|
||||
async function calculateServerFreshnessToken(): Promise<string> {
|
||||
try {
|
||||
const settings = await loadSettings();
|
||||
const habits = await loadHabitsData();
|
||||
const coins = await loadCoinsData();
|
||||
const wishlist = await loadWishlistData();
|
||||
const users = await loadUsersData();
|
||||
|
||||
const dataString = prepareDataForHashing(
|
||||
settings,
|
||||
habits,
|
||||
coins,
|
||||
wishlist,
|
||||
users
|
||||
);
|
||||
const serverToken = await generateCryptoHash(dataString);
|
||||
return serverToken;
|
||||
} catch (error) {
|
||||
console.error("Error calculating server freshness token:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Wishlist specific functions
|
||||
export async function loadWishlistData(): Promise<WishlistData> {
|
||||
const user = await getCurrentUser()
|
||||
@@ -595,3 +625,24 @@ export async function loadServerSettings(): Promise<ServerSettings> {
|
||||
isDemo: !!process.env.DEMO,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the client's data is fresh by comparing its token with the server's token.
|
||||
* @param clientToken The freshness token calculated by the client.
|
||||
* @returns A promise that resolves to an object { isFresh: boolean }.
|
||||
*/
|
||||
export async function checkDataFreshness(clientToken: string): Promise<{ isFresh: boolean }> {
|
||||
try {
|
||||
const serverToken = await calculateServerFreshnessToken();
|
||||
const isFresh = clientToken === serverToken;
|
||||
if (!isFresh) {
|
||||
console.log(`Data freshness check: Stale. Client token: ${clientToken}, Server token: ${serverToken}`);
|
||||
}
|
||||
return { isFresh };
|
||||
} catch (error) {
|
||||
console.error("Error in checkDataFreshness:", error);
|
||||
// If server fails to determine its token, assume client might be stale to be safe,
|
||||
// or handle error reporting differently.
|
||||
return { isFresh: false };
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user