From 97f2c3daa509a1fc0204f0f99105f87ce2c77d2a Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sat, 22 Aug 2026 10:51:40 -0400 Subject: [PATCH] chore(frontend): trim the collection refresh comments Cut the rationale that was repeated at every caller down to one line on the store method, drop the change-history comment from the store test, and narrow errors with `axios.isAxiosError` the way the rest of the frontend does instead of a hand-written cast. Co-Authored-By: Claude Opus 5 (1M context) --- frontend/src/stores/collections.test.ts | 10 +++-- frontend/src/stores/collections.ts | 45 +++++++++---------- .../v2/composables/useRomSync/index.test.ts | 6 +-- .../src/v2/composables/useRomSync/index.ts | 4 +- .../useScanLifecycle/index.test.ts | 2 - .../v2/composables/useScanLifecycle/index.ts | 3 +- .../src/v2/views/Gallery/Collection.test.ts | 16 +++---- frontend/src/v2/views/Gallery/Collection.vue | 22 ++++----- 8 files changed, 48 insertions(+), 60 deletions(-) diff --git a/frontend/src/stores/collections.test.ts b/frontend/src/stores/collections.test.ts index 8d1bdf8d6..09bb37f4a 100644 --- a/frontend/src/stores/collections.test.ts +++ b/frontend/src/stores/collections.test.ts @@ -1,3 +1,4 @@ +import { AxiosError } from "axios"; import { createPinia, setActivePinia } from "pinia"; import { beforeEach, describe, expect, it, vi } from "vitest"; import storeCollections, { type VirtualCollection } from "@/stores/collections"; @@ -12,7 +13,9 @@ vi.mock("@/services/api/collection", () => ({ })); function httpError(status: number) { - return Object.assign(new Error(`HTTP ${status}`), { response: { status } }); + return Object.assign(new AxiosError(`HTTP ${status}`), { + response: { status }, + }); } function virtualCollection(romCount: number): VirtualCollection { @@ -39,9 +42,8 @@ describe("collections store virtual refresh", () => { getVirtualCollections.mockReset(); }); - // A scan or a metadata write landing mid-fetch used to hit the in-flight - // guard and be dropped, leaving the pre-change response cached for the - // session, which is the drift this whole change is about. + // A response in flight left the server before the change did, so it cannot + // stand in for the re-read. it("re-reads after a fetch that was already in flight", async () => { const first = deferred(); getVirtualCollections.mockReturnValueOnce(first.promise); diff --git a/frontend/src/stores/collections.ts b/frontend/src/stores/collections.ts index 4f90992e7..b90df634e 100644 --- a/frontend/src/stores/collections.ts +++ b/frontend/src/stores/collections.ts @@ -1,3 +1,4 @@ +import axios from "axios"; import { uniqBy } from "lodash"; import { defineStore } from "pinia"; import type { @@ -14,11 +15,10 @@ export type VirtualCollection = VirtualCollectionSchema; export type SmartCollection = SmartCollectionSchema; export type CollectionType = Collection | VirtualCollection | SmartCollection; -/** 404 / 403 is the server saying this collection is gone or off limits, which - * is an answer; any other failure means the read didn't happen. */ +/** A 404 or 403 answers the read (gone, or off limits); anything else means + * the read never happened. */ function isGone(error: unknown): boolean { - const status = (error as { response?: { status?: number } })?.response - ?.status; + const status = axios.isAxiosError(error) ? error.response?.status : undefined; return status === 404 || status === 403; } @@ -26,10 +26,7 @@ export default defineStore("collections", { state: () => ({ allCollections: [] as Collection[], virtualCollections: [] as VirtualCollection[], - // The type `virtualCollections` was fetched for, so a refresh knows which - // slice it is re-reading. virtualCollectionType: null as string | null, - // A refresh asked for while a fetch was in flight, to run once it settles. virtualCollectionsStale: false as boolean, smartCollections: [] as SmartCollection[], favoriteCollection: undefined as Collection | undefined, @@ -146,38 +143,36 @@ export default defineStore("collections", { }); }); }, - /** Re-read the loaded virtual collections, whose membership (and so ROM - * count) is derived from ROM metadata that scans and matches rewrite. - * Never rejects: every caller fires it in the background. */ + /** Re-read the loaded virtual collections, whose membership is derived + * from ROM metadata that scans and matches rewrite. Never rejects: every + * caller fires it in the background. */ refreshVirtualCollections(): Promise { const type = this.virtualCollectionType; if (type === null) return Promise.resolve([]); - // A response already in flight left the server before the change did, so - // it cannot be the re-read. Queue one behind it instead of being dropped - // by the in-flight guard. + // A response already in flight left the server before the change did, + // so queue the re-read behind it rather than let the guard drop it. if (this.fetchingVirtualCollections) { this.virtualCollectionsStale = true; return Promise.resolve([]); } return this.fetchVirtualCollections(type).catch(() => []); }, - /** Re-read one collection, refreshing the cached copy on the way through. - * Resolves to null either way: a collection the server says is gone is - * dropped from the cache too, so the caller reads not-found from the cache - * being empty, while a failed read leaves the cached copy to fall back on. */ + /** Re-read one collection and refresh the cached copy. A gone collection + * is dropped from the cache too, so callers read not-found from the cache + * rather than from the null. */ async refreshCollection(id: number): Promise { try { const { data } = await collectionApi.getCollection(id); this.updateCollection(data); return data; } catch (error) { - if (!isGone(error)) { + if (isGone(error)) { + this.allCollections = this.allCollections.filter((c) => c.id !== id); + if (this.favoriteCollection?.id === id) { + this.favoriteCollection = undefined; + } + } else { console.error(error); - return null; - } - this.allCollections = this.allCollections.filter((c) => c.id !== id); - if (this.favoriteCollection?.id === id) { - this.favoriteCollection = undefined; } return null; } @@ -246,8 +241,8 @@ export default defineStore("collections", { ); this._reorderCollections(); }, - // Replaces in place only: the list holds one virtual collection type, and - // an id carries its own type, so inserting could mix them. + // Replaces in place only: the list holds one virtual collection type, so + // inserting could mix types. updateVirtualCollection(collection: VirtualCollection) { this.virtualCollections = this.virtualCollections.map((value) => value.id === collection.id ? collection : value, diff --git a/frontend/src/v2/composables/useRomSync/index.test.ts b/frontend/src/v2/composables/useRomSync/index.test.ts index 73a763ba2..df73316d3 100644 --- a/frontend/src/v2/composables/useRomSync/index.test.ts +++ b/frontend/src/v2/composables/useRomSync/index.test.ts @@ -133,9 +133,9 @@ describe("useRomSync", () => { expect(getRoms).not.toHaveBeenCalled(); }); - // Collection heads and tiles read their ROM count off the store, including - // when the write comes from GameDetails rather than a gallery. - it("applyRomWrite re-reads the virtual collections off the gallery", () => { + // Collection heads and tiles read their count off the store, so the re-read + // is owed even for a write from GameDetails. + it("applyRomWrite re-reads the virtual collections when off the gallery", () => { const collections = storeCollections(); const refresh = vi .spyOn(collections, "refreshVirtualCollections") diff --git a/frontend/src/v2/composables/useRomSync/index.ts b/frontend/src/v2/composables/useRomSync/index.ts index 2a4305019..887cbd2e4 100644 --- a/frontend/src/v2/composables/useRomSync/index.ts +++ b/frontend/src/v2/composables/useRomSync/index.ts @@ -103,8 +103,8 @@ export function useRomSync() { // Read the pre-write copy before `syncCachedRom` overwrites it. const previous = galleryRomsStore.getRomById(rom.id); syncCachedRom(rom); - // Virtual collection membership is derived from the metadata this write - // rewrites, so only the server knows the ROM's new collections and counts. + // Only the server knows which virtual collections this write moved the ROM + // between. void collectionsStore.refreshVirtualCollections(); if (!galleryRomsStore.onGalleryView) return; if (!galleryFilter.isFiltered() && !sortValueChanged(previous, rom)) return; diff --git a/frontend/src/v2/composables/useScanLifecycle/index.test.ts b/frontend/src/v2/composables/useScanLifecycle/index.test.ts index 3c689d4eb..34a6f5397 100644 --- a/frontend/src/v2/composables/useScanLifecycle/index.test.ts +++ b/frontend/src/v2/composables/useScanLifecycle/index.test.ts @@ -129,8 +129,6 @@ describe("installScanLifecycle", () => { expect(scanning.scanStats.scanned_roms).toBe(12); }); - // A scan rewrites the metadata virtual collections derive from, so their - // counts drift like the platform ones. it("re-reads the virtual collections when the scan settles", () => { const collections = storeCollections(); const refresh = vi diff --git a/frontend/src/v2/composables/useScanLifecycle/index.ts b/frontend/src/v2/composables/useScanLifecycle/index.ts index b290d87d3..aac7996bd 100644 --- a/frontend/src/v2/composables/useScanLifecycle/index.ts +++ b/frontend/src/v2/composables/useScanLifecycle/index.ts @@ -186,8 +186,7 @@ export function installScanLifecycle() { scanningStore.setScanStats(stats); scanningStore.setScanning(false); // Reconcile against the backend once the scan settles: pick up anything - // the live updates missed and correct rom_counts that drifted, virtual - // collections included (a scan rewrites the metadata they derive from). + // the live updates missed and correct rom_counts that drifted. void platformsStore.fetchPlatforms(); void collectionsStore.refreshVirtualCollections(); emitter?.emit("snackbarShow", { diff --git a/frontend/src/v2/views/Gallery/Collection.test.ts b/frontend/src/v2/views/Gallery/Collection.test.ts index 36d1844fc..a437ca0b0 100644 --- a/frontend/src/v2/views/Gallery/Collection.test.ts +++ b/frontend/src/v2/views/Gallery/Collection.test.ts @@ -1,5 +1,6 @@ /* eslint-disable vue/one-component-per-file */ import { flushPromises, mount } from "@vue/test-utils"; +import { AxiosError } from "axios"; import { createPinia, setActivePinia } from "pinia"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { defineComponent, nextTick, ref } from "vue"; @@ -351,9 +352,8 @@ describe("Collection view random rom", () => { }); }); -// The store's lists load once per session, and a virtual collection's ROM count -// moves with every scan and match, so a cached count disagrees with the gallery -// below it. +// The store's lists load once per session, so a cached ROM count disagrees +// with the gallery below it. describe("Collection view freshness", () => { beforeEach(() => { setActivePinia(createPinia()); @@ -393,7 +393,7 @@ describe("Collection view freshness", () => { }); // What a finished scan does: the store refetches, and the open page has to - // follow or it drifts again until the next visit. + // follow it. it("adopts the store's copy when a refresh replaces it", async () => { routeState.name = "virtual-collection"; routeState.params = { collection: "collection-zelda" }; @@ -408,8 +408,6 @@ describe("Collection view freshness", () => { expect(wrapper.get(".rom-count").text()).toBe("5"); }); - // Both the route guard and the route watch call the loader per navigation, - // and its read can outlive the route, so only the newest may write. it("ignores a read that lands after the route moved on", async () => { let settleFirst!: (value: { data: Collection }) => void; getCollection.mockReturnValueOnce( @@ -435,11 +433,11 @@ describe("Collection view freshness", () => { expect(wrapper.get(".rom-count").text()).toBe("22"); }); - // A 404 is the server answering, unlike a failed read, so the cached copy - // must not keep a deleted collection on screen. + // A 404 answers, unlike a failed read, so the cached copy must not keep a + // deleted collection on screen. it("shows not-found when the server says the collection is gone", async () => { getCollection.mockRejectedValue( - Object.assign(new Error("HTTP 404"), { response: { status: 404 } }), + Object.assign(new AxiosError("HTTP 404"), { response: { status: 404 } }), ); const wrapper = await mountView(); diff --git a/frontend/src/v2/views/Gallery/Collection.vue b/frontend/src/v2/views/Gallery/Collection.vue index b2f2f5e78..e88dbe1bb 100644 --- a/frontend/src/v2/views/Gallery/Collection.vue +++ b/frontend/src/v2/views/Gallery/Collection.vue @@ -169,11 +169,11 @@ const kindLabel = computed(() => { }); // Leaving for anything that isn't another gallery keeps `currentCollection` -// in place, so neither the load flow nor `onRandomGame` can tell from the id -// alone that the user walked away. +// in place, so the id alone can't see the user walked away. const alive = useIsAlive(); -// Only the newest `loadForRoute` may write to the page or drive the gallery. +// Only the newest `loadForRoute` may write to the page or drive the gallery: +// the guard and the route watch both call it, and its read outlives the route. let loadToken = 0; function kindFromRoute( @@ -212,9 +212,8 @@ function findById(kind: CollectionKind, id: string): AnyCollection | undefined { return collectionsStore.smartCollections.find((c) => String(c.id) === id); } -// The head band renders a ROM count, and the store's lists are loaded once per -// session, so a cached virtual collection counts whatever it held back then -// against a gallery that fetches live. +// The head band renders a ROM count the store's once-per-session lists cannot +// keep in step with the gallery below it. function refreshFromServer( kind: CollectionKind, id: string, @@ -227,14 +226,12 @@ function refreshFromServer( async function loadForRoute(kind: CollectionKind, id: string) { const token = ++loadToken; currentKind.value = kind; - // The list is still loaded, unused here, for the surfaces reachable from - // this page that read it (the add-to-collection dialog). + // The list is unused here, but the surfaces reachable from this page read it + // (the add-to-collection dialog). const [fresh] = await Promise.all([ refreshFromServer(kind, id), ensureLoaded(kind), ]); - // A newer load owns the page: both the route guard and the route watch call - // this per navigation, and the read they wait on can outlive the route. if (token !== loadToken || !alive.value) return; const collection = fresh ?? findById(kind, id); if (!collection) { @@ -275,9 +272,8 @@ watch( }, ); -// Adopt the store's copy when a refresh replaces it, so a scan or a metadata -// write landing while this page is open corrects the head band as well as the -// gallery below. +// Adopt the store's copy when a refresh replaces it, so a scan landing while +// this page is open corrects the head band too. watch( () => findById(currentKind.value, String(route.params.collection)), (fresh) => {