From 428b90139e40b4770c57c19245652c3dce7aed41 Mon Sep 17 00:00:00 2001
From: Robert Andreas Kyllo
Date: Thu, 22 Oct 2026 14:35:20 +0200
Subject: [PATCH 1/6] feat: #15 add album reviews
---
client/src/api/albumDetail.test.ts | 7 ++
client/src/api/albumDetail.ts | 6 ++
client/src/api/client.ts | 10 ++-
client/src/api/reviews.ts | 44 ++++++++++
client/src/api/userIdentity.test.ts | 47 +++++++++++
client/src/api/userIdentity.ts | 31 +++++++
client/src/components/ReviewForm.css | 47 +++++++++++
client/src/components/ReviewForm.test.tsx | 55 +++++++++++++
client/src/components/ReviewForm.tsx | 99 +++++++++++++++++++++++
client/src/pages/AlbumDetailPage.test.tsx | 1 +
client/src/pages/AlbumDetailPage.tsx | 11 ++-
docs/AI-USAGE.md | 1 +
server/src/index.ts | 6 +-
server/src/loaders/index.ts | 16 +++-
server/src/resolvers.ts | 15 +++-
server/src/reviews.test.ts | 17 ++++
server/src/reviews.ts | 97 ++++++++++++++++++++++
server/src/userIdentity.test.ts | 28 +++++++
server/src/userIdentity.ts | 47 +++++++++++
19 files changed, 575 insertions(+), 10 deletions(-)
create mode 100644 client/src/api/reviews.ts
create mode 100644 client/src/api/userIdentity.test.ts
create mode 100644 client/src/api/userIdentity.ts
create mode 100644 client/src/components/ReviewForm.css
create mode 100644 client/src/components/ReviewForm.test.tsx
create mode 100644 client/src/components/ReviewForm.tsx
create mode 100644 server/src/reviews.test.ts
create mode 100644 server/src/reviews.ts
create mode 100644 server/src/userIdentity.test.ts
create mode 100644 server/src/userIdentity.ts
diff --git a/client/src/api/albumDetail.test.ts b/client/src/api/albumDetail.test.ts
index 673388c..108b54f 100644
--- a/client/src/api/albumDetail.test.ts
+++ b/client/src/api/albumDetail.test.ts
@@ -3,7 +3,14 @@ import { buildSchema, validate } from 'graphql';
import { expect, it } from 'vitest';
import { ALBUM_DETAIL } from './albumDetail.js';
+import { DELETE_REVIEW, UPSERT_REVIEW } from './reviews.js';
it('validates the album-detail operation against the repository schema', () => {
expect(validate(buildSchema(schemaSource), ALBUM_DETAIL)).toEqual([]);
});
+
+it('validates review mutations against the repository schema', () => {
+ const schema = buildSchema(schemaSource);
+ expect(validate(schema, UPSERT_REVIEW)).toEqual([]);
+ expect(validate(schema, DELETE_REVIEW)).toEqual([]);
+});
diff --git a/client/src/api/albumDetail.ts b/client/src/api/albumDetail.ts
index addc6b6..693b704 100644
--- a/client/src/api/albumDetail.ts
+++ b/client/src/api/albumDetail.ts
@@ -29,6 +29,7 @@ export type AlbumDetail = {
pageInfo: { hasNextPage: boolean; endCursor: string | null };
totalCount: number;
};
+ myReview: { id: string; rating: number; comment: string } | null;
};
type AlbumDetailData = { album: AlbumDetail | null };
@@ -60,6 +61,11 @@ export const ALBUM_DETAIL: TypedDocumentNode & {
@@ -55,7 +57,9 @@ export const cache = new InMemoryCache({
// ApolloClient coordinates requests and the cache for components under ApolloProvider.
export const apolloClient = new ApolloClient({
cache,
- // HttpLink sends GraphQL operations over HTTP, independently of the /project2/ asset base.
- // TODO(#6): Verify the endpoint and any identity header against the real backend.
- link: new HttpLink({ uri: import.meta.env.VITE_GRAPHQL_URL || '/graphql' }),
+ // Every request carries the simulated identity. It is not authentication;
+ // the server uses it only to separate this browser's reviews and crate.
+ link: setContext((_, { headers }) => ({
+ headers: { ...headers, 'X-User-Id': getUserId() },
+ })).concat(new HttpLink({ uri: import.meta.env.VITE_GRAPHQL_URL || '/graphql' })),
});
diff --git a/client/src/api/reviews.ts b/client/src/api/reviews.ts
new file mode 100644
index 0000000..6782bff
--- /dev/null
+++ b/client/src/api/reviews.ts
@@ -0,0 +1,44 @@
+import { gql } from '@apollo/client';
+import type { TypedDocumentNode } from '@apollo/client';
+
+type ReviewPayload = {
+ review: { id: string; rating: number; comment: string };
+ album: { id: string };
+};
+
+type DeleteReviewPayload = {
+ deletedReviewId: string;
+ album: { id: string };
+};
+
+export const UPSERT_REVIEW: TypedDocumentNode<
+ { upsertReview: ReviewPayload },
+ { input: { albumId: string; rating: number; comment: string } }
+> = gql`
+ mutation UpsertReview($input: UpsertReviewInput!) {
+ upsertReview(input: $input) {
+ review {
+ id
+ rating
+ comment
+ }
+ album {
+ id
+ }
+ }
+ }
+`;
+
+export const DELETE_REVIEW: TypedDocumentNode<
+ { deleteReview: DeleteReviewPayload },
+ { id: string }
+> = gql`
+ mutation DeleteReview($id: ID!) {
+ deleteReview(id: $id) {
+ deletedReviewId
+ album {
+ id
+ }
+ }
+ }
+`;
diff --git a/client/src/api/userIdentity.test.ts b/client/src/api/userIdentity.test.ts
new file mode 100644
index 0000000..0fcd1e3
--- /dev/null
+++ b/client/src/api/userIdentity.test.ts
@@ -0,0 +1,47 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getUserId, USER_ID_STORAGE_KEY } from './userIdentity.js';
+
+const generatedId = '550e8400-e29b-41d4-a716-446655440000';
+
+beforeEach(() => {
+ window.localStorage.clear();
+ vi.spyOn(crypto, 'randomUUID').mockReturnValue(generatedId);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('getUserId', () => {
+ it('creates and persists a UUID the first time', () => {
+ expect(getUserId()).toBe(generatedId);
+ expect(window.localStorage.getItem(USER_ID_STORAGE_KEY)).toBe(generatedId);
+ });
+
+ it('reuses a stored UUID instead of creating a new user', () => {
+ window.localStorage.setItem(USER_ID_STORAGE_KEY, generatedId);
+
+ expect(getUserId()).toBe(generatedId);
+ expect(crypto.randomUUID).not.toHaveBeenCalled();
+ });
+
+ it('replaces malformed storage with a UUID', () => {
+ window.localStorage.setItem(USER_ID_STORAGE_KEY, 'not-a-uuid');
+
+ expect(getUserId()).toBe(generatedId);
+ expect(window.localStorage.getItem(USER_ID_STORAGE_KEY)).toBe(generatedId);
+ });
+
+ it('creates a version 4 UUID when randomUUID is unavailable', () => {
+ vi.stubGlobal('crypto', {
+ getRandomValues: (bytes: Uint8Array) => {
+ bytes.set([...Array(16).keys()]);
+ return bytes;
+ },
+ });
+
+ expect(getUserId()).toBe('00010203-0405-4607-8809-0a0b0c0d0e0f');
+ });
+});
diff --git a/client/src/api/userIdentity.ts b/client/src/api/userIdentity.ts
new file mode 100644
index 0000000..dcc1eb2
--- /dev/null
+++ b/client/src/api/userIdentity.ts
@@ -0,0 +1,31 @@
+export const USER_ID_STORAGE_KEY = 'crate.user-id';
+
+const UUID_PATTERN =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+
+function isUuid(value: string | null): value is string {
+ return value !== null && UUID_PATTERN.test(value);
+}
+
+function createUuid(): string {
+ if (typeof crypto.randomUUID === 'function') return crypto.randomUUID();
+
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
+ bytes[6] = (bytes[6]! & 0x0f) | 0x40;
+ bytes[8] = (bytes[8]! & 0x3f) | 0x80;
+ const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
+}
+
+/**
+ * This is a simulated identity, not authentication. It lets the API associate
+ * a review or crate item with this browser without asking the user to sign in.
+ */
+export function getUserId(): string {
+ const existing = window.localStorage.getItem(USER_ID_STORAGE_KEY);
+ if (isUuid(existing)) return existing.toLowerCase();
+
+ const userId = createUuid();
+ window.localStorage.setItem(USER_ID_STORAGE_KEY, userId);
+ return userId;
+}
diff --git a/client/src/components/ReviewForm.css b/client/src/components/ReviewForm.css
new file mode 100644
index 0000000..c886ef7
--- /dev/null
+++ b/client/src/components/ReviewForm.css
@@ -0,0 +1,47 @@
+.review-form {
+ border-top: 1px solid var(--border);
+ margin-top: 1.25rem;
+ padding-top: 1.25rem;
+}
+.review-form h3 {
+ font-size: 1rem;
+}
+.review-form fieldset {
+ border: 0;
+ margin: 0 0 1rem;
+ padding: 0;
+}
+.review-form legend,
+.review-form > label {
+ display: block;
+ font-weight: 700;
+ margin-bottom: 0.4rem;
+}
+.review-form__ratings {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.4rem 0.75rem;
+}
+.review-form__ratings label {
+ align-items: center;
+ display: flex;
+ gap: 0.25rem;
+}
+.review-form textarea {
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ display: block;
+ resize: vertical;
+ width: 100%;
+}
+.review-form__actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.6rem;
+ margin-top: 1rem;
+}
+.secondary-button {
+ background: transparent;
+ border: 1px solid var(--accent);
+ color: var(--accent);
+}
diff --git a/client/src/components/ReviewForm.test.tsx b/client/src/components/ReviewForm.test.tsx
new file mode 100644
index 0000000..fb82688
--- /dev/null
+++ b/client/src/components/ReviewForm.test.tsx
@@ -0,0 +1,55 @@
+import { MockedProvider } from '@apollo/client/testing/react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { expect, it, vi } from 'vitest';
+
+import { UPSERT_REVIEW } from '../api/reviews.js';
+import ReviewForm from './ReviewForm.js';
+
+it('requires an accessible 1 to 5 star choice before it saves', () => {
+ render(
+
+
+ ,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Publish review' }));
+ expect(screen.getByRole('alert')).toHaveTextContent(
+ 'Choose a rating from 1 to 5 stars',
+ );
+ expect(screen.getAllByRole('radio')).toHaveLength(5);
+ expect(screen.getByRole('radio', { name: '5 stars' })).not.toBeChecked();
+});
+
+it('saves the selected rating and optional comment', async () => {
+ const onChanged = vi.fn(() => Promise.resolve(undefined));
+ render(
+
+
+ ,
+ );
+
+ fireEvent.click(screen.getByRole('radio', { name: '5 stars' }));
+ fireEvent.change(screen.getByRole('textbox', { name: /comment/i }), {
+ target: { value: 'A classic.' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Publish review' }));
+
+ await waitFor(() => expect(onChanged).toHaveBeenCalledOnce());
+});
diff --git a/client/src/components/ReviewForm.tsx b/client/src/components/ReviewForm.tsx
new file mode 100644
index 0000000..89878f5
--- /dev/null
+++ b/client/src/components/ReviewForm.tsx
@@ -0,0 +1,99 @@
+import './ReviewForm.css';
+
+import { useState } from 'react';
+import { useMutation } from '@apollo/client/react';
+
+import { DELETE_REVIEW, UPSERT_REVIEW } from '../api/reviews.js';
+
+type ExistingReview = { id: string; rating: number; comment: string } | null;
+
+interface Props {
+ albumId: string;
+ review: ExistingReview;
+ onChanged: () => Promise;
+}
+
+export default function ReviewForm({ albumId, review, onChanged }: Props) {
+ const [rating, setRating] = useState(review?.rating ?? 0);
+ const [comment, setComment] = useState(review?.comment ?? '');
+ const [error, setError] = useState(null);
+ const [saveReview, saveState] = useMutation(UPSERT_REVIEW);
+ const [deleteReview, deleteState] = useMutation(DELETE_REVIEW);
+ const busy = saveState.loading || deleteState.loading;
+
+ async function submit(event: React.FormEvent) {
+ event.preventDefault();
+ if (rating < 1 || rating > 5) {
+ setError('Choose a rating from 1 to 5 stars.');
+ return;
+ }
+
+ setError(null);
+ try {
+ await saveReview({ variables: { input: { albumId, rating, comment } } });
+ await onChanged();
+ } catch {
+ setError('Your review could not be saved. Please try again.');
+ }
+ }
+
+ async function remove() {
+ if (!review) return;
+ setError(null);
+ try {
+ await deleteReview({ variables: { id: review.id } });
+ await onChanged();
+ } catch {
+ setError('Your review could not be deleted. Please try again.');
+ }
+ }
+
+ return (
+
+ );
+}
diff --git a/client/src/pages/AlbumDetailPage.test.tsx b/client/src/pages/AlbumDetailPage.test.tsx
index 80619a8..0b0a0a0 100644
--- a/client/src/pages/AlbumDetailPage.test.tsx
+++ b/client/src/pages/AlbumDetailPage.test.tsx
@@ -19,6 +19,7 @@ const detail = {
],
averageRating: 4.5,
reviewCount: 1,
+ myReview: null,
reviews: {
edges: [
{
diff --git a/client/src/pages/AlbumDetailPage.tsx b/client/src/pages/AlbumDetailPage.tsx
index 115ae5a..217b45f 100644
--- a/client/src/pages/AlbumDetailPage.tsx
+++ b/client/src/pages/AlbumDetailPage.tsx
@@ -3,6 +3,7 @@ import './AlbumDetailPage.css';
import { useQuery } from '@apollo/client/react';
import { ALBUM_DETAIL } from '../api/albumDetail.js';
+import ReviewForm from '../components/ReviewForm.js';
const REVIEW_PAGE_SIZE = 10;
@@ -17,12 +18,12 @@ function formatDate(value: string): string {
}
export default function AlbumDetailPage({ id }: { id: string }) {
- const { data, loading, error } = useQuery(ALBUM_DETAIL, {
+ const { data, loading, error, refetch } = useQuery(ALBUM_DETAIL, {
variables: { id, reviewFirst: REVIEW_PAGE_SIZE, reviewAfter: null },
});
const discoveryHref = `${import.meta.env.BASE_URL}${window.location.search}`;
- if (loading) {
+ if (loading && !data) {
return (
Loading album…
@@ -88,6 +89,12 @@ export default function AlbumDetailPage({ id }: { id: string }) {
? `Not yet rated · ${album.reviewCount} reviews`
: `${album.averageRating.toFixed(1)} out of 5 · ${album.reviewCount} reviews`}
+
{reviews.length === 0 ? (
No reviews yet.
) : (
diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md
index 6ed770c..6572aa3 100644
--- a/docs/AI-USAGE.md
+++ b/docs/AI-USAGE.md
@@ -59,6 +59,7 @@ the part that matters most.
| 2026-10-19 | erikhfj | opencode | Reviewed #53 against the code rather than as prose. Found the README contradicting its own Implemented section and a smoke test that dropped an expectation while keeping the field in the query. Verified Rachel's other claims, including that `AVERAGE_RATING_DESC` throws, which corrected my own "four sort modes" in the README. |
| 2026-10-19 | erikhfj | opencode | Search state in the URL for #19, with `useSearchState` owning `q`, `sort`, `genres` and `decades`. My first version committed on a 300 ms debounce, which rewrote the URL mid-word and reset the input back through the `query !== previousQuery` branch; it read as the page reloading on every keystroke. Changed so the query reaches the URL only on Search. |
| 2026-10-20 | robertky | Codex (ChatGPT) | Assisted me when I implemented #11: the `album(id:)` resolver, batched loading of album relations, paginated reviews, and a code-split album detail route with tracklist and reviews. I reviewed the parts that AI generated and tests before using it. |
+| 2026-10-22 | robertky | Codex (ChatGPT) | Assisted me when I implemented #15: per-browser user identity, creating/updating/deleting reviews, and the accessible review UI. I reviewed the parts that AI generated and tests before using it. |
| 2026-10-20 | erikhfj | opencode | Processed two co-students' reviews of the project. Both found the same real bug: search matches whole words, so `radio` finds nothing for Radiohead. Their diagnosis was right, but the fix proposed, `to_tsquery` with `:*`, throws on quotes and dashes, which is the whole reason the code uses `websearch_to_tsquery`. Filed #55 to build the prefix query in TypeScript instead. Their rating suggestion exposed something worse: #12 asked for `AVG(review.rating)` as the keyset sort key, an aggregate that moves whenever anyone writes a review. Revised #12 to a trigger-maintained `album.average_rating`, warned #15 not to write the same column, and corrected #18 where a bullet still described a debounce #19 had already removed. |
| 2026-10-22 | erikhfj | opencode | Reviewed #57 and #58 by running the full gate suite on the branches rather than reading them as prose. Six findings on each. One of mine was wrong: I wrote that `App.tsx` was the only file in the repo carrying a UTF-8 BOM. It is one of four, and three predate that PR entirely. Posted a correction rather than leaving the error standing. Recorded here because a wrong review is as much a failure of control as a wrong patch. |
diff --git a/server/src/index.ts b/server/src/index.ts
index 5a41b96..ad4b3ed 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -4,6 +4,7 @@ import { createSchema, createYoga } from 'graphql-yoga';
import { db } from './db/client.js';
import { createLoaders } from './loaders/index.js';
import { resolvers, type Context } from './resolvers.js';
+import { parseUserId } from './userIdentity.js';
// The API contract is the schema.graphql at the repository root, shared with
// the client. The path is the same from src/ (dev) and dist/ (production).
@@ -12,7 +13,10 @@ const typeDefs = readFileSync(new URL('../../schema.graphql', import.meta.url),
const yoga = createYoga({
schema: createSchema({ typeDefs, resolvers }),
// New loaders per request, so batching never leaks between requests.
- context: () => ({ db, loaders: createLoaders(db) }),
+ context: ({ request }) => {
+ const userId = parseUserId(request.headers.get('x-user-id'));
+ return { db, userId, loaders: createLoaders(db, userId) };
+ },
});
const port = Number(process.env.PORT ?? 3001);
diff --git a/server/src/loaders/index.ts b/server/src/loaders/index.ts
index 96b5c83..9e246f2 100644
--- a/server/src/loaders/index.ts
+++ b/server/src/loaders/index.ts
@@ -1,5 +1,5 @@
import DataLoader from 'dataloader';
-import { asc, avg, count, eq, inArray } from 'drizzle-orm';
+import { and, asc, avg, count, eq, inArray } from 'drizzle-orm';
import type { Db } from '../db/client.js';
import {
albumArtist,
@@ -10,6 +10,7 @@ import {
review,
track,
} from '../db/schema.js';
+import type { ReviewRecord } from '../reviews.js';
type Named = { id: number; name: string };
export type TrackRecord = {
@@ -29,7 +30,7 @@ export type TrackRecord = {
* Created fresh for every request (see index.ts), so nothing is cached between
* requests or shared between users.
*/
-export function createLoaders(db: Db) {
+export function createLoaders(db: Db, userId: string | null) {
return {
artistsByAlbum: new DataLoader(async (albumIds) => {
const rows = await db
@@ -85,6 +86,17 @@ export function createLoaders(db: Db) {
return albumIds.map((id) => averages.get(id) ?? null);
}),
+ myReviewByAlbum: new DataLoader(async (albumIds) => {
+ if (!userId) return albumIds.map(() => null);
+
+ const rows = await db
+ .select()
+ .from(review)
+ .where(and(eq(review.userId, userId), inArray(review.albumId, [...albumIds])));
+ const byAlbum = new Map(rows.map((row) => [row.albumId, row]));
+ return albumIds.map((id) => byAlbum.get(id) ?? null);
+ }),
+
userById: new DataLoader(
async (userIds) => {
const rows = await db
diff --git a/server/src/resolvers.ts b/server/src/resolvers.ts
index f674541..c35f502 100644
--- a/server/src/resolvers.ts
+++ b/server/src/resolvers.ts
@@ -13,7 +13,9 @@ import {
sortKey,
type AlbumSearchInput,
} from './search/search.js';
-export type Context = { db: Db; loaders: Loaders };
+import { removeReview, saveReview, type UpsertReviewInput } from './reviews.js';
+
+export type Context = { db: Db; loaders: Loaders; userId: string | null };
type AlbumRow = { id: number; title: string; releaseYear: number | null };
@@ -160,7 +162,8 @@ async function searchAlbums(db: Db, { input, first, after }: SearchArgs) {
};
}
-// Search and album detail resolve relations through request-scoped loaders.
+// Fields not listed here (tracks, ratings, reviews, crate) arrive with their
+// own issues.
export const resolvers = {
Query: {
searchAlbums: (_: unknown, args: SearchArgs, ctx: Context) =>
@@ -186,6 +189,8 @@ export const resolvers = {
ctx.loaders.reviewCountByAlbum.load(album.id),
averageRating: (album: AlbumRow, _: unknown, ctx: Context) =>
ctx.loaders.averageRatingByAlbum.load(album.id),
+ myReview: (album: AlbumRow, _: unknown, ctx: Context) =>
+ ctx.loaders.myReviewByAlbum.load(album.id),
reviews: (album: AlbumRow, args: ReviewArgs, ctx: Context) =>
reviewsForAlbum(ctx, album.id, args),
},
@@ -196,4 +201,10 @@ export const resolvers = {
return user;
},
},
+ Mutation: {
+ upsertReview: (_: unknown, { input }: { input: UpsertReviewInput }, ctx: Context) =>
+ saveReview(ctx.db, ctx.userId, input),
+ deleteReview: (_: unknown, { id }: { id: string }, ctx: Context) =>
+ removeReview(ctx.db, ctx.userId, id),
+ },
};
diff --git a/server/src/reviews.test.ts b/server/src/reviews.test.ts
new file mode 100644
index 0000000..36e2cf8
--- /dev/null
+++ b/server/src/reviews.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+
+import { removeReview, saveReview } from './reviews.js';
+
+const userId = '550e8400-e29b-41d4-a716-446655440000';
+
+describe('review input validation', () => {
+ it.each([0, 6, 1.5])('rejects rating %s before database work', async (rating) => {
+ await expect(
+ saveReview({} as never, userId, { albumId: '1', rating, comment: '' }),
+ ).rejects.toThrow('Rating must be an integer between 1 and 5');
+ });
+
+ it('rejects a missing user before deleting a review', async () => {
+ await expect(removeReview({} as never, null, '1')).rejects.toThrow('X-User-Id');
+ });
+});
diff --git a/server/src/reviews.ts b/server/src/reviews.ts
new file mode 100644
index 0000000..35f0caa
--- /dev/null
+++ b/server/src/reviews.ts
@@ -0,0 +1,97 @@
+import { and, eq } from 'drizzle-orm';
+import { GraphQLError } from 'graphql';
+
+import type { Db } from './db/client.js';
+import { album, review } from './db/schema.js';
+import { ensureUser, requireUserId } from './userIdentity.js';
+
+export type ReviewRecord = {
+ id: number;
+ userId: string;
+ albumId: number;
+ rating: number;
+ comment: string;
+ createdAt: Date;
+ updatedAt: Date;
+};
+
+export type AlbumRecord = { id: number; title: string; releaseYear: number | null };
+
+export type UpsertReviewInput = {
+ albumId: string;
+ rating: number;
+ comment: string;
+};
+
+function parseAlbumId(value: string): number {
+ const id = Number(value);
+ if (!Number.isSafeInteger(id) || id < 1) throw new GraphQLError('Invalid album id.');
+ return id;
+}
+
+function validateRating(rating: number): void {
+ if (!Number.isInteger(rating) || rating < 1 || rating > 5) {
+ throw new GraphQLError('Rating must be an integer between 1 and 5.');
+ }
+}
+
+async function findAlbum(db: Db, id: number): Promise {
+ const [found] = await db
+ .select({ id: album.id, title: album.title, releaseYear: album.releaseYear })
+ .from(album)
+ .where(eq(album.id, id));
+
+ if (!found) throw new GraphQLError('Album not found.');
+ return found;
+}
+
+export async function saveReview(
+ db: Db,
+ userId: string | null,
+ input: UpsertReviewInput,
+): Promise<{ review: ReviewRecord; album: AlbumRecord }> {
+ const ownerId = requireUserId(userId);
+ const albumId = parseAlbumId(input.albumId);
+ validateRating(input.rating);
+
+ const albumRecord = await findAlbum(db, albumId);
+ await ensureUser(db, ownerId);
+
+ const [saved] = await db
+ .insert(review)
+ .values({
+ userId: ownerId,
+ albumId,
+ rating: input.rating,
+ comment: input.comment.trim(),
+ })
+ .onConflictDoUpdate({
+ target: [review.userId, review.albumId],
+ set: { rating: input.rating, comment: input.comment.trim(), updatedAt: new Date() },
+ })
+ .returning();
+
+ if (!saved) throw new Error('Could not save review.');
+ return { review: saved, album: albumRecord };
+}
+
+export async function removeReview(
+ db: Db,
+ userId: string | null,
+ reviewId: string,
+): Promise<{ deletedReviewId: string; album: AlbumRecord }> {
+ const ownerId = requireUserId(userId);
+ const id = parseAlbumId(reviewId);
+
+ const [deleted] = await db
+ .delete(review)
+ .where(and(eq(review.id, id), eq(review.userId, ownerId)))
+ .returning({ id: review.id, albumId: review.albumId });
+
+ if (!deleted) throw new GraphQLError('Review not found for this user.');
+
+ return {
+ deletedReviewId: String(deleted.id),
+ album: await findAlbum(db, deleted.albumId),
+ };
+}
diff --git a/server/src/userIdentity.test.ts b/server/src/userIdentity.test.ts
new file mode 100644
index 0000000..0744664
--- /dev/null
+++ b/server/src/userIdentity.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+
+import { displayNameFor, parseUserId, requireUserId } from './userIdentity.js';
+
+const userId = '550e8400-e29b-41d4-a716-446655440000';
+
+describe('parseUserId', () => {
+ it('accepts UUIDs and normalises their casing', () => {
+ expect(parseUserId(userId.toUpperCase())).toBe(userId);
+ });
+
+ it.each([null, '', 'not-a-uuid', '550e8400-e29b-61d4-a716-446655440000'])(
+ 'treats %j as anonymous',
+ (value) => {
+ expect(parseUserId(value)).toBeNull();
+ },
+ );
+});
+
+describe('simulated users', () => {
+ it('derives a stable display name from the UUID', () => {
+ expect(displayNameFor(userId)).toBe('Listener 550e8400');
+ });
+
+ it('rejects writes without a valid identity', () => {
+ expect(() => requireUserId(null)).toThrow('X-User-Id');
+ });
+});
diff --git a/server/src/userIdentity.ts b/server/src/userIdentity.ts
new file mode 100644
index 0000000..a596c80
--- /dev/null
+++ b/server/src/userIdentity.ts
@@ -0,0 +1,47 @@
+import { eq } from 'drizzle-orm';
+import { GraphQLError } from 'graphql';
+
+import type { Db } from './db/client.js';
+import { appUser } from './db/schema.js';
+
+export type UserIdentity = {
+ id: string;
+ displayName: string;
+};
+
+const UUID_PATTERN =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+
+export function parseUserId(value: string | null): string | null {
+ return value && UUID_PATTERN.test(value) ? value.toLowerCase() : null;
+}
+
+export function displayNameFor(userId: string): string {
+ return `Listener ${userId.slice(0, 8)}`;
+}
+
+export function requireUserId(userId: string | null): string {
+ if (!userId) {
+ throw new GraphQLError('A valid X-User-Id header is required for this action.');
+ }
+
+ return userId;
+}
+
+export async function ensureUser(db: Db, userId: string): Promise {
+ const displayName = displayNameFor(userId);
+
+ await db
+ .insert(appUser)
+ .values({ id: userId, displayName })
+ .onConflictDoNothing({ target: appUser.id });
+
+ const [user] = await db
+ .select({ id: appUser.id, displayName: appUser.displayName })
+ .from(appUser)
+ .where(eq(appUser.id, userId));
+
+ if (!user) throw new Error('Could not create the simulated user.');
+
+ return user;
+}
From 5e8adfaac741cd5e46a3d4b4d7fc37390a1fad2f Mon Sep 17 00:00:00 2001
From: Robert Andreas Kyllo
Date: Fri, 23 Oct 2026 19:39:40 +0200
Subject: [PATCH 2/6] fix: #15 improve review validation
---
client/src/components/ReviewForm.test.tsx | 1 +
client/src/components/ReviewForm.tsx | 10 ++++++----
server/src/reviews.test.ts | 6 ++++++
server/src/reviews.ts | 16 +++++++++++++---
4 files changed, 26 insertions(+), 7 deletions(-)
diff --git a/client/src/components/ReviewForm.test.tsx b/client/src/components/ReviewForm.test.tsx
index fb82688..1c2f9fb 100644
--- a/client/src/components/ReviewForm.test.tsx
+++ b/client/src/components/ReviewForm.test.tsx
@@ -18,6 +18,7 @@ it('requires an accessible 1 to 5 star choice before it saves', () => {
);
expect(screen.getAllByRole('radio')).toHaveLength(5);
expect(screen.getByRole('radio', { name: '5 stars' })).not.toBeChecked();
+ expect(screen.getByRole('textbox', { name: /comment/i })).toHaveAttribute('maxlength', '2000');
});
it('saves the selected rating and optional comment', async () => {
diff --git a/client/src/components/ReviewForm.tsx b/client/src/components/ReviewForm.tsx
index 89878f5..464b87d 100644
--- a/client/src/components/ReviewForm.tsx
+++ b/client/src/components/ReviewForm.tsx
@@ -6,6 +6,7 @@ import { useMutation } from '@apollo/client/react';
import { DELETE_REVIEW, UPSERT_REVIEW } from '../api/reviews.js';
type ExistingReview = { id: string; rating: number; comment: string } | null;
+const MAX_COMMENT_LENGTH = 2000;
interface Props {
albumId: string;
@@ -32,8 +33,8 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) {
try {
await saveReview({ variables: { input: { albumId, rating, comment } } });
await onChanged();
- } catch {
- setError('Your review could not be saved. Please try again.');
+ } catch (caught) {
+ setError(caught instanceof Error ? caught.message : 'Your review could not be saved.');
}
}
@@ -43,8 +44,8 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) {
try {
await deleteReview({ variables: { id: review.id } });
await onChanged();
- } catch {
- setError('Your review could not be deleted. Please try again.');
+ } catch (caught) {
+ setError(caught instanceof Error ? caught.message : 'Your review could not be deleted.');
}
}
@@ -76,6 +77,7 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) {
value={comment}
onChange={(event) => setComment(event.target.value)}
disabled={busy}
+ maxLength={MAX_COMMENT_LENGTH}
rows={4}
/>
{error && {error}
}
diff --git a/server/src/reviews.test.ts b/server/src/reviews.test.ts
index 36e2cf8..e0537c5 100644
--- a/server/src/reviews.test.ts
+++ b/server/src/reviews.test.ts
@@ -14,4 +14,10 @@ describe('review input validation', () => {
it('rejects a missing user before deleting a review', async () => {
await expect(removeReview({} as never, null, '1')).rejects.toThrow('X-User-Id');
});
+
+ it('rejects an overlong comment before database work', async () => {
+ await expect(
+ saveReview({} as never, userId, { albumId: '1', rating: 5, comment: 'x'.repeat(2001) }),
+ ).rejects.toThrow('Comment must be at most 2000 characters');
+ });
});
diff --git a/server/src/reviews.ts b/server/src/reviews.ts
index 35f0caa..dc27f4d 100644
--- a/server/src/reviews.ts
+++ b/server/src/reviews.ts
@@ -23,6 +23,8 @@ export type UpsertReviewInput = {
comment: string;
};
+const MAX_COMMENT_LENGTH = 2000;
+
function parseAlbumId(value: string): number {
const id = Number(value);
if (!Number.isSafeInteger(id) || id < 1) throw new GraphQLError('Invalid album id.');
@@ -35,6 +37,12 @@ function validateRating(rating: number): void {
}
}
+function validateComment(comment: string): void {
+ if (comment.length > MAX_COMMENT_LENGTH) {
+ throw new GraphQLError(`Comment must be at most ${MAX_COMMENT_LENGTH} characters.`);
+ }
+}
+
async function findAlbum(db: Db, id: number): Promise {
const [found] = await db
.select({ id: album.id, title: album.title, releaseYear: album.releaseYear })
@@ -53,6 +61,8 @@ export async function saveReview(
const ownerId = requireUserId(userId);
const albumId = parseAlbumId(input.albumId);
validateRating(input.rating);
+ const comment = input.comment.trim();
+ validateComment(comment);
const albumRecord = await findAlbum(db, albumId);
await ensureUser(db, ownerId);
@@ -63,15 +73,15 @@ export async function saveReview(
userId: ownerId,
albumId,
rating: input.rating,
- comment: input.comment.trim(),
+ comment,
})
.onConflictDoUpdate({
target: [review.userId, review.albumId],
- set: { rating: input.rating, comment: input.comment.trim(), updatedAt: new Date() },
+ set: { rating: input.rating, comment },
})
.returning();
- if (!saved) throw new Error('Could not save review.');
+ if (!saved) throw new GraphQLError('Could not save review.');
return { review: saved, album: albumRecord };
}
From 9c39954bbbdf8a4eae4fcc9be0aab832201f622a Mon Sep 17 00:00:00 2001
From: Robert Andreas Kyllo
Date: Fri, 23 Oct 2026 19:44:56 +0200
Subject: [PATCH 3/6] style: #15 format review validation
---
client/src/components/ReviewForm.test.tsx | 5 ++++-
client/src/components/ReviewForm.tsx | 8 ++++++--
server/src/reviews.test.ts | 6 +++++-
3 files changed, 15 insertions(+), 4 deletions(-)
diff --git a/client/src/components/ReviewForm.test.tsx b/client/src/components/ReviewForm.test.tsx
index 1c2f9fb..6783cee 100644
--- a/client/src/components/ReviewForm.test.tsx
+++ b/client/src/components/ReviewForm.test.tsx
@@ -18,7 +18,10 @@ it('requires an accessible 1 to 5 star choice before it saves', () => {
);
expect(screen.getAllByRole('radio')).toHaveLength(5);
expect(screen.getByRole('radio', { name: '5 stars' })).not.toBeChecked();
- expect(screen.getByRole('textbox', { name: /comment/i })).toHaveAttribute('maxlength', '2000');
+ expect(screen.getByRole('textbox', { name: /comment/i })).toHaveAttribute(
+ 'maxlength',
+ '2000',
+ );
});
it('saves the selected rating and optional comment', async () => {
diff --git a/client/src/components/ReviewForm.tsx b/client/src/components/ReviewForm.tsx
index 464b87d..650cc5d 100644
--- a/client/src/components/ReviewForm.tsx
+++ b/client/src/components/ReviewForm.tsx
@@ -34,7 +34,9 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) {
await saveReview({ variables: { input: { albumId, rating, comment } } });
await onChanged();
} catch (caught) {
- setError(caught instanceof Error ? caught.message : 'Your review could not be saved.');
+ setError(
+ caught instanceof Error ? caught.message : 'Your review could not be saved.',
+ );
}
}
@@ -45,7 +47,9 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) {
await deleteReview({ variables: { id: review.id } });
await onChanged();
} catch (caught) {
- setError(caught instanceof Error ? caught.message : 'Your review could not be deleted.');
+ setError(
+ caught instanceof Error ? caught.message : 'Your review could not be deleted.',
+ );
}
}
diff --git a/server/src/reviews.test.ts b/server/src/reviews.test.ts
index e0537c5..6f19814 100644
--- a/server/src/reviews.test.ts
+++ b/server/src/reviews.test.ts
@@ -17,7 +17,11 @@ describe('review input validation', () => {
it('rejects an overlong comment before database work', async () => {
await expect(
- saveReview({} as never, userId, { albumId: '1', rating: 5, comment: 'x'.repeat(2001) }),
+ saveReview({} as never, userId, {
+ albumId: '1',
+ rating: 5,
+ comment: 'x'.repeat(2001),
+ }),
).rejects.toThrow('Comment must be at most 2000 characters');
});
});
From 49ec46fbd732ad3b144e1231f1c0095f2b0dcc51 Mon Sep 17 00:00:00 2001
From: Robert Andreas Kyllo
Date: Sun, 25 Oct 2026 12:35:02 +0100
Subject: [PATCH 4/6] fix: #15 paginate and announce reviews
---
client/src/components/ReviewForm.test.tsx | 3 ++
client/src/components/ReviewForm.tsx | 26 +++++++++-
client/src/pages/AlbumDetailPage.test.tsx | 62 ++++++++++++++++++++++-
client/src/pages/AlbumDetailPage.tsx | 56 +++++++++++++++++---
4 files changed, 137 insertions(+), 10 deletions(-)
diff --git a/client/src/components/ReviewForm.test.tsx b/client/src/components/ReviewForm.test.tsx
index 6783cee..5703111 100644
--- a/client/src/components/ReviewForm.test.tsx
+++ b/client/src/components/ReviewForm.test.tsx
@@ -56,4 +56,7 @@ it('saves the selected rating and optional comment', async () => {
fireEvent.click(screen.getByRole('button', { name: 'Publish review' }));
await waitFor(() => expect(onChanged).toHaveBeenCalledOnce());
+ const status = await screen.findByRole('status');
+ expect(status).toHaveTextContent('Your review was published.');
+ expect(status).toHaveFocus();
});
diff --git a/client/src/components/ReviewForm.tsx b/client/src/components/ReviewForm.tsx
index 650cc5d..e0e6b95 100644
--- a/client/src/components/ReviewForm.tsx
+++ b/client/src/components/ReviewForm.tsx
@@ -1,6 +1,6 @@
import './ReviewForm.css';
-import { useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { useMutation } from '@apollo/client/react';
import { DELETE_REVIEW, UPSERT_REVIEW } from '../api/reviews.js';
@@ -18,10 +18,25 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) {
const [rating, setRating] = useState(review?.rating ?? 0);
const [comment, setComment] = useState(review?.comment ?? '');
const [error, setError] = useState(null);
+ const [status, setStatus] = useState(null);
+ const statusRef = useRef(null);
const [saveReview, saveState] = useMutation(UPSERT_REVIEW);
const [deleteReview, deleteState] = useMutation(DELETE_REVIEW);
const busy = saveState.loading || deleteState.loading;
+ useEffect(() => {
+ setRating(review?.rating ?? 0);
+ setComment(review?.comment ?? '');
+ }, [review?.id, review?.rating, review?.comment]);
+
+ useEffect(() => {
+ if (status) statusRef.current?.focus();
+ }, [status]);
+
+ function announce(message: string) {
+ setStatus(message);
+ }
+
async function submit(event: React.FormEvent) {
event.preventDefault();
if (rating < 1 || rating > 5) {
@@ -30,9 +45,11 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) {
}
setError(null);
+ setStatus(null);
try {
await saveReview({ variables: { input: { albumId, rating, comment } } });
await onChanged();
+ announce(review ? 'Your review was updated.' : 'Your review was published.');
} catch (caught) {
setError(
caught instanceof Error ? caught.message : 'Your review could not be saved.',
@@ -43,9 +60,11 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) {
async function remove() {
if (!review) return;
setError(null);
+ setStatus(null);
try {
await deleteReview({ variables: { id: review.id } });
await onChanged();
+ announce('Your review was deleted.');
} catch (caught) {
setError(
caught instanceof Error ? caught.message : 'Your review could not be deleted.',
@@ -85,6 +104,11 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) {
rows={4}
/>
{error && {error}
}
+ {status && (
+
+ {status}
+
+ )}
{busy ? 'Saving…' : review ? 'Save changes' : 'Publish review'}
diff --git a/client/src/pages/AlbumDetailPage.test.tsx b/client/src/pages/AlbumDetailPage.test.tsx
index 0b0a0a0..533b34b 100644
--- a/client/src/pages/AlbumDetailPage.test.tsx
+++ b/client/src/pages/AlbumDetailPage.test.tsx
@@ -1,5 +1,5 @@
import { MockedProvider } from '@apollo/client/testing/react';
-import { render, screen, within } from '@testing-library/react';
+import { fireEvent, render, screen, within } from '@testing-library/react';
import { expect, it } from 'vitest';
import { ALBUM_DETAIL } from '../api/albumDetail.js';
@@ -84,3 +84,63 @@ it('shows a useful error state when an album cannot be loaded', async () => {
`${import.meta.env.BASE_URL}?q=Abbey&sort=TITLE_ASC`,
);
});
+
+it('loads the next page of reviews on request', async () => {
+ const firstPage = {
+ ...detail,
+ reviewCount: 2,
+ reviews: {
+ ...detail.reviews,
+ totalCount: 2,
+ pageInfo: { hasNextPage: true, endCursor: 'cursor-1' },
+ },
+ };
+ const secondPage = {
+ ...detail,
+ reviewCount: 2,
+ reviews: {
+ edges: [
+ {
+ cursor: 'cursor-2',
+ node: {
+ id: '2',
+ rating: 4,
+ comment: 'Still brilliant.',
+ createdAt: '2026-10-19T12:00:00.000Z',
+ user: { id: 'user-2', displayName: 'Listener user-2' },
+ },
+ },
+ ],
+ totalCount: 2,
+ pageInfo: { hasNextPage: false, endCursor: 'cursor-2' },
+ },
+ };
+ render(
+
+
+ ,
+ );
+
+ await screen.findByRole('heading', { name: 'Abbey Road' });
+ fireEvent.click(screen.getByRole('button', { name: 'Load more reviews' }));
+
+ expect(await screen.findByText('Still brilliant.')).toBeInTheDocument();
+ expect(screen.getByText('A classic.')).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', { name: 'Load more reviews' }),
+ ).not.toBeInTheDocument();
+});
diff --git a/client/src/pages/AlbumDetailPage.tsx b/client/src/pages/AlbumDetailPage.tsx
index 217b45f..cd9b69a 100644
--- a/client/src/pages/AlbumDetailPage.tsx
+++ b/client/src/pages/AlbumDetailPage.tsx
@@ -1,5 +1,6 @@
import './AlbumDetailPage.css';
+import { useState } from 'react';
import { useQuery } from '@apollo/client/react';
import { ALBUM_DETAIL } from '../api/albumDetail.js';
@@ -18,11 +19,47 @@ function formatDate(value: string): string {
}
export default function AlbumDetailPage({ id }: { id: string }) {
- const { data, loading, error, refetch } = useQuery(ALBUM_DETAIL, {
+ const [loadingMoreReviews, setLoadingMoreReviews] = useState(false);
+ const [reviewsError, setReviewsError] = useState(null);
+ const { data, loading, error, refetch, fetchMore } = useQuery(ALBUM_DETAIL, {
variables: { id, reviewFirst: REVIEW_PAGE_SIZE, reviewAfter: null },
});
const discoveryHref = `${import.meta.env.BASE_URL}${window.location.search}`;
+ async function loadMoreReviews() {
+ const after = data?.album?.reviews.pageInfo.endCursor;
+ if (!after) return;
+
+ setLoadingMoreReviews(true);
+ setReviewsError(null);
+ try {
+ await fetchMore({
+ variables: { reviewAfter: after },
+ updateQuery: (previous, { fetchMoreResult }) => {
+ if (!previous.album || !fetchMoreResult.album) return previous;
+ return {
+ album: {
+ ...fetchMoreResult.album,
+ reviews: {
+ ...fetchMoreResult.album.reviews,
+ edges: [
+ ...previous.album.reviews.edges,
+ ...fetchMoreResult.album.reviews.edges,
+ ],
+ },
+ },
+ };
+ },
+ });
+ } catch (caught) {
+ setReviewsError(
+ caught instanceof Error ? caught.message : 'Could not load more reviews.',
+ );
+ } finally {
+ setLoadingMoreReviews(false);
+ }
+ }
+
if (loading && !data) {
return (
@@ -89,12 +126,7 @@ export default function AlbumDetailPage({ id }: { id: string }) {
? `Not yet rated · ${album.reviewCount} reviews`
: `${album.averageRating.toFixed(1)} out of 5 · ${album.reviewCount} reviews`}
-
+
{reviews.length === 0 ? (
No reviews yet.
) : (
@@ -118,8 +150,16 @@ export default function AlbumDetailPage({ id }: { id: string }) {
)}
{album.reviews.pageInfo.hasNextPage && (
- More reviews can be loaded when pagination is added.
+ void loadMoreReviews()}
+ disabled={loadingMoreReviews}
+ >
+ {loadingMoreReviews ? 'Loading reviews…' : 'Load more reviews'}
+
)}
+ {reviewsError && {reviewsError}
}
From 76032f1b851b0d9252f5a261b1e792c67478405e Mon Sep 17 00:00:00 2001
From: Robert Andreas Kyllo
Date: Sun, 25 Oct 2026 23:08:58 +0100
Subject: [PATCH 5/6] fix: #15 avoid review form lint error
---
client/src/components/ReviewForm.tsx | 7 ++-----
1 file changed, 2 insertions(+), 5 deletions(-)
diff --git a/client/src/components/ReviewForm.tsx b/client/src/components/ReviewForm.tsx
index e0e6b95..80ca9c2 100644
--- a/client/src/components/ReviewForm.tsx
+++ b/client/src/components/ReviewForm.tsx
@@ -24,11 +24,6 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) {
const [deleteReview, deleteState] = useMutation(DELETE_REVIEW);
const busy = saveState.loading || deleteState.loading;
- useEffect(() => {
- setRating(review?.rating ?? 0);
- setComment(review?.comment ?? '');
- }, [review?.id, review?.rating, review?.comment]);
-
useEffect(() => {
if (status) statusRef.current?.focus();
}, [status]);
@@ -64,6 +59,8 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) {
try {
await deleteReview({ variables: { id: review.id } });
await onChanged();
+ setRating(0);
+ setComment('');
announce('Your review was deleted.');
} catch (caught) {
setError(
From da3cf58ea44c9ec613465ebb02cb8afe3a8b7445 Mon Sep 17 00:00:00 2001
From: Robert Andreas Kyllo
Date: Mon, 26 Oct 2026 01:39:10 +0100
Subject: [PATCH 6/6] fix: #15 align review timestamps with detail schema
---
server/src/reviews.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/server/src/reviews.ts b/server/src/reviews.ts
index dc27f4d..78a4b5f 100644
--- a/server/src/reviews.ts
+++ b/server/src/reviews.ts
@@ -11,7 +11,7 @@ export type ReviewRecord = {
albumId: number;
rating: number;
comment: string;
- createdAt: Date;
+ createdAt: string;
updatedAt: Date;
};