Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
102 changes: 17 additions & 85 deletions client/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
import './App.css';

import SearchForm from './components/SearchForm.js';
import ResultsLayout from './components/ResultsLayout.js';
import { lazy, Suspense } from 'react';

import { useAlbumSearch } from './hooks/useAlbumSearch.js';
import { useSearchHistory } from './hooks/useSearchHistory.js';
import Link from './components/Link.js';
import DiscoveryPage from './pages/DiscoveryPage.js';
import { appHref, stripBasePath, useLocation } from './router.js';

export default function App() {
const basePath = import.meta.env.BASE_URL.replace(/\/$/, '');
const discoveryHref = import.meta.env.BASE_URL;
const pathname = window.location.pathname.startsWith(basePath)
? window.location.pathname.slice(basePath.length) || '/'
: window.location.pathname;
const location = useLocation();
const discoveryHref = appHref('/');
const crateHref = appHref('/crate');
const pathname = stripBasePath(location.pathname);
const detailMatch = /^\/album\/(\d+)$/.exec(pathname);
const detailId = detailMatch?.[1];
const isCrate = pathname === '/crate';
Expand All @@ -24,15 +22,18 @@ export default function App() {
</a>
<header className="site-header">
<nav className="navigation" aria-label="Main navigation">
<a className="brand" href={discoveryHref}>
<Link className="brand" href={discoveryHref}>
Crate<span aria-hidden="true">●</span>
</a>
<a href={discoveryHref} aria-current={detailId || isCrate ? undefined : 'page'}>
</Link>
<Link
href={discoveryHref}
aria-current={detailId || isCrate ? undefined : 'page'}
>
Discover
</a>
<a href={`${basePath}/crate`} aria-current={isCrate ? 'page' : undefined}>
</Link>
<Link href={crateHref} aria-current={isCrate ? 'page' : undefined}>
Your crate
</a>
</Link>
</nav>
</header>
{detailId ? (
Expand All @@ -48,7 +49,7 @@ export default function App() {
</main>
}
>
<AlbumDetailPage id={detailId} />
<AlbumDetailPage key={detailId} id={detailId} />
</Suspense>
) : isCrate ? (
<Suspense
Expand All @@ -68,74 +69,5 @@ export default function App() {
);
}

function DiscoveryPage() {
const search = useAlbumSearch();
const history = useSearchHistory();

function submitSearch(query: string) {
search.search(query);
history.recordSearch(query);
}

return (
<main id="main" className="discovery-main" tabIndex={-1}>
<section className="search-section" aria-labelledby="search-heading">
<div className="search-section__content">
<p className="eyebrow">Your next favorite is in here</p>
<h1 id="search-heading">
Music worth
<br /> <em>holding onto.</em>
</h1>
<p className="tagline">
Search, rate and collect albums you’ll want to return to.
</p>
<SearchForm query={search.query} onSearch={submitSearch} history={history} />
<p className="hero-credit">
Photo by{' '}
<a href="https://unsplash.com/photos/black-turntable-on-brown-wooden-table-TcSckNRL9J8">
Kevin McCutcheon on Unsplash
</a>
</p>
</div>
</section>
<div id="catalogue" className="catalogue-layout">
<ResultsLayout
filters={{
genres: search.filters.genres,
decades: search.filters.decades,
countries: search.filters.countries,
reviewed: search.filters.reviewed,
genreFacets: search.facets.genres,
decadeFacets: search.facets.decades,
countryFacets: search.facets.countries,
reviewedCount: search.facets.reviewedCount,
onGenresChange: search.setGenres,
onDecadesChange: search.setDecades,
onCountriesChange: search.setCountries,
onReviewedChange: search.setReviewed,
onClear: search.clearFilters,
}}
albums={search.albums}
totalCount={search.totalCount}
hasQuery={search.hasQuery}
sort={search.sort}
onSortChange={search.setSort}
loading={search.loading}
loadingMore={search.loadingMore}
pageError={search.pageError}
hasNextPage={search.hasNextPage}
onLoadMore={search.loadMore}
canLoadAutomatically={search.canLoadAutomatically}
onLoadMoreAutomatically={search.loadMoreAutomatically}
retrying={search.retrying}
error={search.error}
onRetry={search.retry}
onReset={search.resetSearch}
/>
</div>
</main>
);
}

const AlbumDetailPage = lazy(() => import('./pages/AlbumDetailPage.js'));
const CratePage = lazy(() => import('./pages/CratePage.js'));
99 changes: 99 additions & 0 deletions client/src/api/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { buildSchema, print, validate, type FieldNode } from 'graphql';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { cache } from './client.js';
import { MY_CRATE } from './crate.js';
import { updateCacheAfterReviewMutation } from './reviews.js';
import { SEARCH_ALBUMS, SEARCH_ALBUMS_PAGE } from './searchAlbums.js';
import { MY_SEARCH_HISTORY } from './searchHistory.js';
import type {
Expand Down Expand Up @@ -196,3 +198,100 @@ describe('searchAlbums cache policy', () => {
expect(read()?.searchAlbums.pageInfo.endCursor).toBe('cursor-2');
});
});

describe('myCrate cache policy and review mutation cache updates', () => {
function crateResult(ids: string[], endCursor: string | null, hasNextPage = true) {
return {
myCrate: {
edges: ids.map((id) => ({
cursor: `crate-${id}`,
node: {
__typename: 'CrateItem' as const,
id: `item-${id}`,
addedAt: '2026-11-20T12:00:00.000Z',
album: {
__typename: 'Album' as const,
id,
title: `Album ${id}`,
releaseYear: 1990,
musicBrainzReleaseGroupId: null,
averageRating: null,
reviewCount: 0,
isInCrate: true,
artists: [],
genres: [],
},
},
})),
pageInfo: { hasNextPage, endCursor },
totalCount: 3,
},
};
}

it('merges myCrate pages using the shared cursor connection policy', () => {
cache.writeQuery({
query: MY_CRATE,
variables: { first: 2, after: null },
data: crateResult(['1', '2'], 'crate-2', true),
});
cache.writeQuery({
query: MY_CRATE,
variables: { first: 2, after: 'crate-2' },
data: crateResult(['2', '3'], 'crate-3', false),
});

const crate = cache.readQuery({
query: MY_CRATE,
variables: { first: 2, after: null },
})?.myCrate;

expect(crate?.edges.map((edge) => edge.node.album.id)).toEqual(['1', '2', '3']);
expect(crate?.pageInfo).toEqual({ hasNextPage: false, endCursor: 'crate-3' });
});

it('updates normalized album stats in myCrate and evicts stale searchAlbums after review mutations', () => {
write(result(['1', '2'], 'cursor-2'));
cache.writeQuery({
query: MY_CRATE,
variables: { first: 20, after: null },
data: crateResult(['1'], 'crate-1', false),
});

updateCacheAfterReviewMutation(cache, {
id: '1',
averageRating: 4.5,
reviewCount: 2,
myReview: {
id: 'r1',
rating: 5,
comment: 'Great record',
createdAt: '2026-11-20T12:00:00.000Z',
updatedAt: '2026-11-20T12:00:00.000Z',
},
});

const crateAfterUpsert = cache.readQuery({
query: MY_CRATE,
variables: { first: 20, after: null },
})?.myCrate;
expect(crateAfterUpsert?.edges[0]?.node.album.averageRating).toBe(4.5);
expect(crateAfterUpsert?.edges[0]?.node.album.reviewCount).toBe(2);
expect(read()).toBeNull();

// Deleting the last review resets album rating/count and clears myReview.
updateCacheAfterReviewMutation(cache, {
id: '1',
averageRating: null,
reviewCount: 0,
myReview: null,
});

const crateAfterDelete = cache.readQuery({
query: MY_CRATE,
variables: { first: 20, after: null },
})?.myCrate;
expect(crateAfterDelete?.edges[0]?.node.album.averageRating).toBeNull();
expect(crateAfterDelete?.edges[0]?.node.album.reviewCount).toBe(0);
});
});
102 changes: 49 additions & 53 deletions client/src/api/client.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,65 @@
import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client';
import type { Reference, StoreObject } from '@apollo/client';
import type { FieldFunctionOptions, Reference, StoreObject } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

import type { AlbumConnection } from './searchAlbums.js';
import { getUserId } from './userIdentity.js';

type CachedEdge = { cursor: string; node: Reference | StoreObject };

type CursorConnection = {
pageInfo: { hasNextPage: boolean; endCursor: string | null };
edges: CachedEdge[];
};

// Album nodes are normalized references inside the cache, not query-result objects.
// A Load more page (SEARCH_ALBUMS_PAGE) carries only edges and pageInfo.
type CachedConnection = Partial<Omit<AlbumConnection, 'edges' | 'pageInfo'>> &
Pick<AlbumConnection, 'pageInfo'> & {
edges: { cursor: string; node: Reference | StoreObject }[];
edges: CachedEdge[];
};

// The crate is one list per user, so no arguments belong in its cache key; only
// the paging argument decides whether this is another page or a refresh.
type CachedCrate = {
pageInfo: { hasNextPage: boolean; endCursor: string | null };
edges: { cursor: string; node: Reference | StoreObject }[];
type CachedCrate = CursorConnection & {
totalCount: number;
};

/**
* Shared keyset-cursor pagination merger for normalized GraphQL connections.
* Replaces on first-page refreshes, ignores stale/repeated continuations,
* deduplicates appended edges by node ID, and preserves first-page fields
* omitted by lighter continuation queries.
*/
function mergeCursorConnection<T extends CursorConnection>(
existing: T | undefined,
incoming: T,
{ args, readField }: FieldFunctionOptions,
): T {
// A first-page refresh must replace any previously accumulated pages.
if (!args?.after) return incoming;

// Only append to the current tail. Ignore repeated or stale continuations.
if (!existing || args.after !== existing.pageInfo.endCursor) {
return existing ?? incoming;
}

const ids = new Set(existing.edges.map((edge) => readField<string>('id', edge.node)));
const edges = [...existing.edges];

for (const edge of incoming.edges) {
const id = readField<string>('id', edge.node);

if (!ids.has(id)) {
ids.add(id);
edges.push(edge);
}
}

// Later pages may leave out first-page aggregates (counts/facets), so existing stays.
return { ...existing, ...incoming, edges };
}

// InMemoryCache stores server results and shares album records by their IDs.
export const cache = new InMemoryCache({
typePolicies: {
Expand All @@ -33,69 +73,25 @@ export const cache = new InMemoryCache({
searchAlbums: {
// Each complete search input gets its own list; paging arguments do not.
keyArgs: ['input'],

merge(
existing: CachedConnection | undefined,
incoming: CachedConnection,
{ args, readField },
options,
): CachedConnection {
// A first-page refresh must replace any previously accumulated pages.
if (!args?.after) return incoming;

// Only append to the current tail. Ignore repeated or stale continuations.
if (!existing || args.after !== existing.pageInfo.endCursor) {
return existing ?? incoming;
}

const ids = new Set(
existing.edges.map((edge) => readField<string>('id', edge.node)),
);
const edges = [...existing.edges];

for (const edge of incoming.edges) {
const id = readField<string>('id', edge.node);

if (!ids.has(id)) {
ids.add(id);
edges.push(edge);
}
}

// Later pages leave out the count and facets, so the first page's stay.
return { ...existing, ...incoming, edges };
return mergeCursorConnection(existing, incoming, options);
},
},

myCrate: {
// One crate per user, so there is nothing to key on: `after` is paging,
// not a different list. The user id never reaches the cache key.
keyArgs: false,

merge(
existing: CachedCrate | undefined,
incoming: CachedCrate,
{ args, readField },
options,
): CachedCrate {
// A reload of the first page replaces whatever was accumulated.
if (!args?.after) return incoming;
if (!existing || args.after !== existing.pageInfo.endCursor) {
return existing ?? incoming;
}

const ids = new Set(
existing.edges.map((edge) => readField<string>('id', edge.node)),
);
const edges = [...existing.edges];

for (const edge of incoming.edges) {
const id = readField<string>('id', edge.node);
if (!ids.has(id)) {
ids.add(id);
edges.push(edge);
}
}

return { ...incoming, edges };
return mergeCursorConnection(existing, incoming, options);
},
},
},
Expand Down
Loading