feat: use a queue in user pictures localstorage

This commit is contained in:
imperosol
2026-05-06 21:35:15 +02:00
parent 387e5fe0a3
commit 2f9a4c3d4f
+19 -19
View File
@@ -22,35 +22,35 @@ document.addEventListener("alpine:init", () => {
albums: [] as Album[], albums: [] as Album[],
async fetchPictures(): Promise<PictureSchema[]> { async fetchPictures(): Promise<PictureSchema[]> {
const localStorageKey = `user${config.userId}Pictures`; // Check the cache before hitting the API.
const localStorageInvalidationKey = `user${config.userId}PicturesNumber`; const localStorageKey = "userPictures";
const lastCachedNumber = localStorage.getItem(localStorageInvalidationKey); const cacheContent: { userId: number; pictures: PictureSchema[] }[] = JSON.parse(
localStorage.getItem(localStorageKey) || "[]",
);
const userPictures = cacheContent.find((obj) => obj.userId === config.userId);
if ( if (
lastCachedNumber !== null && userPictures !== undefined &&
Number.parseInt(lastCachedNumber, 10) === config.nbPictures userPictures.pictures.length === config.nbPictures
) { ) {
return JSON.parse(localStorage.getItem(localStorageKey)); // The cached value is considered valid
// if it contains the right amount of pictures.
// This amount is known because it is given in the template.
return userPictures.pictures;
} }
const pictures = await paginated(picturesFetchPictures, { const pictures = await paginated(picturesFetchPictures, {
// biome-ignore lint/style/useNamingConvention: from python api // biome-ignore lint/style/useNamingConvention: from python api
query: { users_identified: [config.userId] }, query: { users_identified: [config.userId] },
} as PicturesFetchPicturesData); } as PicturesFetchPicturesData);
cacheContent.push({ userId: config.userId, pictures: pictures });
try { try {
localStorage.setItem(localStorageInvalidationKey, config.nbPictures.toString()); // cache only the pictures of the last 4 visited profiles
localStorage.setItem(localStorageKey, JSON.stringify(pictures)); localStorage.setItem(localStorageKey, JSON.stringify(cacheContent.slice(-4)));
} catch { } catch {
// an exception is raised if the localstorage is entirely filled // an exception is raised if the localstorage is entirely filled.
// so just delete all cached user pictures. // To be as safe as possible, delete the cached pictures.
// A cache hit is not worth the page breaking. // A cache hit is not worth the page breaking.
Object.keys(localStorage) localStorage.removeItem(localStorageKey);
.filter(
(key) =>
key.startsWith("user") &&
(key.endsWith("Pictures") || key.endsWith("PicturesNumber")),
)
.forEach((key) => {
localStorage.removeItem(key);
});
} }
return pictures; return pictures;
}, },