From bdf0782ba4399d821fc437fbf440c9f0f54a89c5 Mon Sep 17 00:00:00 2001 From: SivertEikrem Date: Tue, 10 Nov 2026 19:24:47 +0100 Subject: [PATCH 1/4] feat(backend): add review table and input validation (#33) --- .../1794333349979_create-review-table.sql | 20 ++++++ backend/src/review-input.test.ts | 68 +++++++++++++++++++ backend/src/review-input.ts | 63 +++++++++++++++++ 3 files changed, 151 insertions(+) create mode 100644 backend/migrations/1794333349979_create-review-table.sql create mode 100644 backend/src/review-input.test.ts create mode 100644 backend/src/review-input.ts diff --git a/backend/migrations/1794333349979_create-review-table.sql b/backend/migrations/1794333349979_create-review-table.sql new file mode 100644 index 0000000..3690a6a --- /dev/null +++ b/backend/migrations/1794333349979_create-review-table.sql @@ -0,0 +1,20 @@ +-- Up Migration + +-- Student reviews. A user is an anonymous ID stored in the browser until we have login. +CREATE TABLE review ( + id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + wine_id integer NOT NULL REFERENCES wine (id) ON DELETE CASCADE, + user_id uuid NOT NULL, + rating smallint NOT NULL CHECK (rating BETWEEN 1 AND 6), -- die roll + comment text CHECK (char_length(comment) <= 500), + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (wine_id, user_id) -- one review per user per wine +); + +-- For "Nylig dømt": the newest reviews first. +CREATE INDEX review_created_at ON review (created_at DESC); + +-- Down Migration + +DROP TABLE review; \ No newline at end of file diff --git a/backend/src/review-input.test.ts b/backend/src/review-input.test.ts new file mode 100644 index 0000000..fcaf361 --- /dev/null +++ b/backend/src/review-input.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from 'vitest'; +import { authorName, MAX_COMMENT_LENGTH, validateReviewInput } from './review-input'; + +const USER_ID = '3f2a9c1e-8b4d-4e2a-9f1c-2b7d6e5a4c3b'; + +describe('validateReviewInput', () => { + it('accepts a valid review and converts the wine ID to a number', () => { + const review = validateReviewInput({ wineId: '100062', userId: USER_ID, rating: 5, comment: 'Godt!' }); + expect(review).toEqual({ wineId: 100062, userId: USER_ID, rating: 5, comment: 'Godt!' }); + }); + + it('accepts every side of the die', () => { + for (const rating of [1, 2, 3, 4, 5, 6]) { + expect(validateReviewInput({ wineId: '1', userId: USER_ID, rating }).rating).toBe(rating); + } + }); + + it('rejects ratings outside the die and half values', () => { + for (const rating of [0, 7, -1, 3.5]) { + expect(() => validateReviewInput({ wineId: '1', userId: USER_ID, rating })).toThrow('rating'); + } + }); + + it('stores a blank comment as no comment', () => { + expect(validateReviewInput({ wineId: '1', userId: USER_ID, rating: 4, comment: ' ' }).comment).toBeNull(); + expect(validateReviewInput({ wineId: '1', userId: USER_ID, rating: 4 }).comment).toBeNull(); + }); + + it('trims the comment', () => { + expect(validateReviewInput({ wineId: '1', userId: USER_ID, rating: 4, comment: ' Fin ' }).comment).toBe('Fin'); + }); + + it('rejects a comment that is too long', () => { + const comment = 'a'.repeat(MAX_COMMENT_LENGTH + 1); + expect(() => validateReviewInput({ wineId: '1', userId: USER_ID, rating: 4, comment })).toThrow('comment'); + }); + + it('rejects invalid wine IDs', () => { + for (const wineId of ['abc', '-1', '0', '1.5']) { + expect(() => validateReviewInput({ wineId, userId: USER_ID, rating: 4 })).toThrow('wine ID'); + } + }); + + it('rejects a user ID that is not a UUID', () => { + expect(() => validateReviewInput({ wineId: '1', userId: 'student-1', rating: 4 })).toThrow('user ID'); + }); + + it('gives a BAD_USER_INPUT error so the frontend can show the message', () => { + try { + validateReviewInput({ wineId: '1', userId: USER_ID, rating: 9 }); + } catch (error) { + expect((error as { extensions: { code: string } }).extensions.code).toBe('BAD_USER_INPUT'); + } + expect.assertions(1); + }); +}); + +describe('authorName', () => { + it('gives the same name for the same user', () => { + expect(authorName(USER_ID)).toBe(authorName(USER_ID)); + }); + + it('looks like "Student #" and four digits, and never shows the ID', () => { + const name = authorName(USER_ID); + expect(name).toMatch(/^Student #\d{4}$/); + expect(name).not.toContain(USER_ID.slice(0, 8)); + }); +}); \ No newline at end of file diff --git a/backend/src/review-input.ts b/backend/src/review-input.ts new file mode 100644 index 0000000..d038ee6 --- /dev/null +++ b/backend/src/review-input.ts @@ -0,0 +1,63 @@ +// Checks and cleans the input to saveReview. Kept separate from the database so it is easy to test. +import { GraphQLError } from 'graphql'; + +export const MIN_RATING = 1; +export const MAX_RATING = 6; // Die roll. Change together with the CHECK in the review migration. +export const MAX_COMMENT_LENGTH = 500; + +export interface ReviewInput { + wineId: string; + userId: string; + rating: number; + comment?: string | null; +} + +export interface ValidReview { + wineId: number; + userId: string; + rating: number; + comment: string | null; +} + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +function badInput(message: string): GraphQLError { + return new GraphQLError(message, { extensions: { code: 'BAD_USER_INPUT' } }); +} + +export function validateWineId(value: string): number { + const id = Number(value); + if (!Number.isInteger(id) || id <= 0) throw badInput('Invalid wine ID.'); + return id; +} + +export function validateUserId(value: string): string { + if (!UUID.test(value)) throw badInput('Invalid user ID.'); + return value.toLowerCase(); +} + +export function validateReviewInput(input: ReviewInput): ValidReview { + const { rating } = input; + if (!Number.isInteger(rating) || rating < MIN_RATING || rating > MAX_RATING) { + throw badInput(`The rating must be a whole number from ${MIN_RATING} to ${MAX_RATING}.`); + } + + // An empty or blank comment is stored as no comment. + const comment = input.comment?.trim() || null; + if (comment && comment.length > MAX_COMMENT_LENGTH) { + throw badInput(`The comment can be at most ${MAX_COMMENT_LENGTH} characters.`); + } + + return { + wineId: validateWineId(input.wineId), + userId: validateUserId(input.userId), + rating, + comment, + }; +} + +/** A stable display name made from the anonymous ID, e.g. "Student #4821". The ID itself is never shown. */ +export function authorName(userId: string): string { + const number = (parseInt(userId.replace(/-/g, '').slice(0, 8), 16) % 9000) + 1000; + return `Student #${number}`; +} \ No newline at end of file From 7a6ade2a2e1c8940dd0ae9c5007204ef79ca3c8b Mon Sep 17 00:00:00 2001 From: SivertEikrem Date: Tue, 10 Nov 2026 19:37:28 +0100 Subject: [PATCH 2/4] feat(backend): add GraphQL API for student reviews (#33) --- backend/src/resolvers.ts | 116 ++++++++++++++++++++++++++++++++++++++- backend/src/schema.ts | 44 +++++++++++++++ docs/api.md | 40 +++++++++++++- 3 files changed, 198 insertions(+), 2 deletions(-) diff --git a/backend/src/resolvers.ts b/backend/src/resolvers.ts index 01988e2..0878cdc 100644 --- a/backend/src/resolvers.ts +++ b/backend/src/resolvers.ts @@ -1,5 +1,13 @@ // Resolvers: the functions that fetch data for each field in the schema. +import { GraphQLError } from 'graphql'; import { pool } from './db'; +import { + authorName, + validateReviewInput, + validateUserId, + validateWineId, + type ReviewInput, +} from './review-input'; import { buildFilterOptionsQueries, buildWinesQuery, @@ -8,6 +16,9 @@ import { type WinesArgs, } from './wine-query'; +// The most reviews one query can ask for. +const MAX_REVIEWS = 50; + // A row from the wine table, as returned by pg. interface WineRow { id: number; @@ -29,6 +40,17 @@ interface WineRow { community_count: number; } +// A row from the review table. +interface ReviewRow { + id: number; + wine_id: number; + user_id: string; + rating: number; + comment: string | null; + created_at: Date; + updated_at: Date; +} + // Converts database names (snake_case) to GraphQL names (camelCase). function toWine(row: WineRow) { return { @@ -52,6 +74,24 @@ function toWine(row: WineRow) { }; } +// The user ID is left out on purpose, so it is never sent to other users. +function toReview(row: ReviewRow) { + return { + id: String(row.id), + wineId: row.wine_id, + rating: row.rating, + comment: row.comment, + author: authorName(row.user_id), + createdAt: row.created_at.toISOString(), + updatedAt: row.updated_at.toISOString(), + }; +} + +/** Keeps "first" between 1 and MAX_REVIEWS, whatever the frontend sends. */ +function limitReviews(first: number | null | undefined, fallback: number): number { + return Math.min(Math.max(first ?? fallback, 1), MAX_REVIEWS); +} + async function filterOptions( args: FilterArgs, group: keyof ReturnType, @@ -88,7 +128,7 @@ export const resolvers = { async wine(_parent: unknown, args: { id: string }) { const id = Number(args.id); if (!Number.isInteger(id)) return null; - const result = await pool.query('SELECT * FROM wine WHERE id = $1', [id]); + const result = await pool.query('SELECT * FROM wine WHERE id = $1', [id]); return result.rows[0] ? toWine(result.rows[0]) : null; }, @@ -96,6 +136,54 @@ export const resolvers = { filterOptions(_parent: unknown, args: FilterArgs) { return args; }, + + async recentReviews(_parent: unknown, args: { first?: number | null }) { + const result = await pool.query( + 'SELECT * FROM review ORDER BY created_at DESC, id DESC LIMIT $1', + [limitReviews(args.first, 5)], + ); + return result.rows.map(toReview); + }, + + async myReview(_parent: unknown, args: { wineId: string; userId: string }) { + const result = await pool.query( + 'SELECT * FROM review WHERE wine_id = $1 AND user_id = $2', + [validateWineId(args.wineId), validateUserId(args.userId)], + ); + return result.rows[0] ? toReview(result.rows[0]) : null; + }, + }, + + Mutation: { + async saveReview(_parent: unknown, args: { input: ReviewInput }) { + const review = validateReviewInput(args.input); + try { + // Adds the review, or updates the old one if this user has already reviewed the wine. + const result = await pool.query( + `INSERT INTO review (wine_id, user_id, rating, comment) + VALUES ($1, $2, $3, $4) + ON CONFLICT (wine_id, user_id) + DO UPDATE SET rating = EXCLUDED.rating, comment = EXCLUDED.comment, updated_at = now() + RETURNING *`, + [review.wineId, review.userId, review.rating, review.comment], + ); + return toReview(result.rows[0]); + } catch (error) { + // 23503 = foreign key violation: the wine does not exist. + if ((error as { code?: string }).code === '23503') { + throw new GraphQLError('Wine not found.', { extensions: { code: 'BAD_USER_INPUT' } }); + } + throw error; + } + }, + + async deleteReview(_parent: unknown, args: { wineId: string; userId: string }) { + const result = await pool.query( + 'DELETE FROM review WHERE wine_id = $1 AND user_id = $2', + [validateWineId(args.wineId), validateUserId(args.userId)], + ); + return (result.rowCount ?? 0) > 0; + }, }, FilterOptions: { @@ -104,4 +192,30 @@ export const resolvers = { grapes: (args: FilterArgs) => filterOptions(args, 'grapes'), harmonize: (args: FilterArgs) => filterOptions(args, 'harmonize'), }, + + // Fields on Wine that are not columns in the wine table. They only run when the frontend asks for them. + Wine: { + async studentRating(wine: { id: string }) { + const result = await pool.query<{ average: number | null; count: number }>( + 'SELECT AVG(rating)::float AS average, COUNT(*)::int AS count FROM review WHERE wine_id = $1', + [Number(wine.id)], + ); + return result.rows[0]; + }, + + async reviews(wine: { id: string }, args: { first?: number | null }) { + const result = await pool.query( + 'SELECT * FROM review WHERE wine_id = $1 ORDER BY updated_at DESC, id DESC LIMIT $2', + [Number(wine.id), limitReviews(args.first, 10)], + ); + return result.rows.map(toReview); + }, + }, + + Review: { + async wine(review: { wineId: number }) { + const result = await pool.query('SELECT * FROM wine WHERE id = $1', [review.wineId]); + return toWine(result.rows[0]); + }, + }, }; \ No newline at end of file diff --git a/backend/src/schema.ts b/backend/src/schema.ts index 96fd132..2751422 100644 --- a/backend/src/schema.ts +++ b/backend/src/schema.ts @@ -40,6 +40,10 @@ export const typeDefs = `#graphql "Average X-Wines rating (1-5), or null if nobody has rated the wine." communityRating: Float communityRatingCount: Int! + "Average die roll from students on Kork & Krone." + studentRating: StudentRating! + "The newest student reviews of this wine." + reviews(first: Int = 10): [Review!]! } type WineEdge { @@ -74,6 +78,32 @@ export const typeDefs = `#graphql harmonize: [FilterOption!]! } + type StudentRating { + "Average die roll (1-6), or null if no student has reviewed the wine." + average: Float + count: Int! + } + + type Review { + id: ID! + "Die roll from 1 to 6." + rating: Int! + comment: String + "Display name such as 'Student #4821'. The user ID is never shown." + author: String! + createdAt: String! + updatedAt: String! + wine: Wine! + } + + input ReviewInput { + wineId: ID! + "The anonymous ID stored in the browser." + userId: ID! + rating: Int! + comment: String + } + type Query { "Search, filter and sort wines. Use pageInfo.endCursor as 'after' to load the next page." wines( @@ -88,5 +118,19 @@ export const typeDefs = `#graphql "Values for the filter panel. The counts follow the search and the filters in the other groups." filterOptions(search: String, filter: WineFilter): FilterOptions! + + "The newest student reviews across all wines." + recentReviews(first: Int = 5): [Review!]! + + "The user's own review of a wine, so the form can show it again." + myReview(wineId: ID!, userId: ID!): Review + } + + type Mutation { + "Adds a review, or updates the user's earlier review of the same wine." + saveReview(input: ReviewInput!): Review! + + "Deletes the user's review of a wine. Returns false if there was none." + deleteReview(wineId: ID!, userId: ID!): Boolean! } `; \ No newline at end of file diff --git a/docs/api.md b/docs/api.md index 84da29b..3e20453 100644 --- a/docs/api.md +++ b/docs/api.md @@ -52,4 +52,42 @@ During development, Vite forwards `/graphql` to the backend. On the VM, Apache f ## Tests -`npm test` in `backend/` runs the unit tests for parsing and query building. \ No newline at end of file +`npm test` in `backend/` runs the unit tests for parsing and query building. + +## Student reviews + +A review is a die roll from 1 to 6 and an optional comment (max 500 characters). +There is no login yet, so the frontend creates a random UUID once (`crypto.randomUUID()`), +stores it in localStorage and sends it as `userId`. Treat it like a password: the API never +returns it, and reviews are shown with a display name such as "Student #8086". + +Each user has one review per wine. Saving again replaces the old review, including the comment. + +```graphql +mutation SaveReview($input: ReviewInput!) { + saveReview(input: $input) { id rating comment author updatedAt } +} + +query WineReviews($id: ID!) { + wine(id: $id) { + studentRating { average count } + reviews(first: 10) { id rating comment author updatedAt } + } +} + +query MyReview($wineId: ID!, $userId: ID!) { + myReview(wineId: $wineId, userId: $userId) { rating comment } +} + +query RecentReviews { + recentReviews(first: 5) { id rating comment author createdAt wine { id name type } } +} + +mutation DeleteReview($wineId: ID!, $userId: ID!) { + deleteReview(wineId: $wineId, userId: $userId) +} +``` + +Invalid input (a rating outside 1–6, a too long comment, an unknown wine) gives an error +with the code `BAD_USER_INPUT` and a message that can be shown to the user. +`first` is limited to 50. \ No newline at end of file From a70904a7dfaca455f07a614b502c273fe3c2b1b5 Mon Sep 17 00:00:00 2001 From: SivertEikrem Date: Wed, 11 Nov 2026 11:45:51 +0100 Subject: [PATCH 3/4] fix(backend): batch review lookups with DataLoader and give students unique names (#33) --- .../1794333349979_create-review-table.sql | 19 +- backend/package-lock.json | 7 + backend/package.json | 1 + backend/src/loaders.ts | 100 +++++++ backend/src/resolvers.ts | 282 ++++++++---------- backend/src/review-input.test.ts | 10 +- backend/src/review-input.ts | 7 +- backend/src/server.ts | 40 +-- docs/api.md | 6 +- 9 files changed, 286 insertions(+), 186 deletions(-) create mode 100644 backend/src/loaders.ts diff --git a/backend/migrations/1794333349979_create-review-table.sql b/backend/migrations/1794333349979_create-review-table.sql index 3690a6a..469df2c 100644 --- a/backend/migrations/1794333349979_create-review-table.sql +++ b/backend/migrations/1794333349979_create-review-table.sql @@ -1,20 +1,31 @@ -- Up Migration --- Student reviews. A user is an anonymous ID stored in the browser until we have login. +-- Students who have written a review. The UUID comes from the browser until we have login. +-- The id is shown as "Student #", so every student gets a unique name. +CREATE TABLE student ( + id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + user_id uuid NOT NULL UNIQUE, + created_at timestamptz NOT NULL DEFAULT now() +); + CREATE TABLE review ( id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, wine_id integer NOT NULL REFERENCES wine (id) ON DELETE CASCADE, - user_id uuid NOT NULL, + student_id integer NOT NULL REFERENCES student (id) ON DELETE CASCADE, rating smallint NOT NULL CHECK (rating BETWEEN 1 AND 6), -- die roll comment text CHECK (char_length(comment) <= 500), created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), - UNIQUE (wine_id, user_id) -- one review per user per wine + UNIQUE (wine_id, student_id) -- one review per student per wine ); -- For "Nylig dømt": the newest reviews first. CREATE INDEX review_created_at ON review (created_at DESC); +-- For a wine's reviews, newest first. +CREATE INDEX review_wine_updated ON review (wine_id, updated_at DESC); + -- Down Migration -DROP TABLE review; \ No newline at end of file +DROP TABLE review; +DROP TABLE student; \ No newline at end of file diff --git a/backend/package-lock.json b/backend/package-lock.json index c94be32..d8f7d66 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -11,6 +11,7 @@ "dependencies": { "@apollo/server": "^5.5.1", "@as-integrations/express5": "^1.1.2", + "dataloader": "^2.2.3", "express": "^5.2.1", "graphql": "^16.14.2", "pg": "^8.23.1" @@ -1972,6 +1973,12 @@ "node": ">=16.0.0" } }, + "node_modules/dataloader": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/dataloader/-/dataloader-2.2.3.tgz", + "integrity": "sha512-y2krtASINtPFS1rSDjacrFgn1dcUuoREVabwlOGOe4SdxenREqwjwjElAdwvbGM7kgZz9a3KVicWR7vcz8rnzA==", + "license": "MIT" + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", diff --git a/backend/package.json b/backend/package.json index 597e09c..65f6a1c 100644 --- a/backend/package.json +++ b/backend/package.json @@ -19,6 +19,7 @@ "dependencies": { "@apollo/server": "^5.5.1", "@as-integrations/express5": "^1.1.2", + "dataloader": "^2.2.3", "express": "^5.2.1", "graphql": "^16.14.2", "pg": "^8.23.1" diff --git a/backend/src/loaders.ts b/backend/src/loaders.ts new file mode 100644 index 0000000..b7349e4 --- /dev/null +++ b/backend/src/loaders.ts @@ -0,0 +1,100 @@ +// DataLoaders collect the lookups made while one request is resolved, and run each kind as one query. +// Without them, a page of 50 wines would run one query per wine for each field (the "N+1 problem"). +import DataLoader from 'dataloader'; +import { pool } from './db'; + +// A row from the wine table, as returned by pg. +export interface WineRow { + id: number; + name: string; + type: string; + elaborate: string | null; + grapes: string[]; + harmonize: string[]; + abv: string | null; // pg returns numeric columns as strings + body: string | null; + acidity: string | null; + country_code: string | null; + country: string | null; + region_name: string | null; + winery_name: string | null; + website: string | null; + vintages: number[]; + community_avg: string | null; + community_count: number; +} + +// A row from the review table. +export interface ReviewRow { + id: number; + wine_id: number; + student_id: number; + rating: number; + comment: string | null; + created_at: Date; + updated_at: Date; +} + +export interface StudentRating { + average: number | null; + count: number; +} + +/** New loaders for every request, so data is never cached between users or requests. */ +export function createLoaders() { + const wines = new DataLoader(async (ids) => { + const result = await pool.query('SELECT * FROM wine WHERE id = ANY($1)', [[...ids]]); + const byId = new Map(result.rows.map((row) => [row.id, row])); + return ids.map((id) => byId.get(id) ?? null); + }); + + const studentRatings = new DataLoader(async (wineIds) => { + const result = await pool.query<{ wine_id: number; average: number; count: number }>( + `SELECT wine_id, AVG(rating)::float AS average, COUNT(*)::int AS count + FROM review + WHERE wine_id = ANY($1) + GROUP BY wine_id`, + [[...wineIds]], + ); + const byWine = new Map(result.rows.map((row) => [row.wine_id, row])); + return wineIds.map((id) => { + const row = byWine.get(id); + return row ? { average: row.average, count: row.count } : { average: null, count: 0 }; + }); + }); + + // One loader per page size, because "first" is part of the query. + const reviewLoaders = new Map>(); + + function reviews(first: number) { + let loader = reviewLoaders.get(first); + if (!loader) { + loader = new DataLoader(async (wineIds) => { + // row_number() numbers each wine's reviews, newest first, so we keep the first N per wine. + const result = await pool.query( + `SELECT id, wine_id, student_id, rating, comment, created_at, updated_at + FROM ( + SELECT *, row_number() OVER (PARTITION BY wine_id ORDER BY updated_at DESC, id DESC) AS position + FROM review + WHERE wine_id = ANY($1) + ) numbered + WHERE position <= $2 + ORDER BY updated_at DESC, id DESC`, + [[...wineIds], first], + ); + return wineIds.map((id) => result.rows.filter((row) => row.wine_id === id)); + }); + reviewLoaders.set(first, loader); + } + return loader; + } + + return { wines, studentRatings, reviews }; +} + +export type Loaders = ReturnType; + +/** What every resolver gets as its third argument. */ +export interface Context { + loaders: Loaders; +} \ No newline at end of file diff --git a/backend/src/resolvers.ts b/backend/src/resolvers.ts index 0878cdc..0265c05 100644 --- a/backend/src/resolvers.ts +++ b/backend/src/resolvers.ts @@ -1,6 +1,7 @@ // Resolvers: the functions that fetch data for each field in the schema. import { GraphQLError } from 'graphql'; import { pool } from './db'; +import { type Context, type ReviewRow, type WineRow } from './loaders'; import { authorName, validateReviewInput, @@ -19,71 +20,39 @@ import { // The most reviews one query can ask for. const MAX_REVIEWS = 50; -// A row from the wine table, as returned by pg. -interface WineRow { - id: number; - name: string; - type: string; - elaborate: string | null; - grapes: string[]; - harmonize: string[]; - abv: string | null; // pg returns numeric columns as strings - body: string | null; - acidity: string | null; - country_code: string | null; - country: string | null; - region_name: string | null; - winery_name: string | null; - website: string | null; - vintages: number[]; - community_avg: string | null; - community_count: number; -} - -// A row from the review table. -interface ReviewRow { - id: number; - wine_id: number; - user_id: string; - rating: number; - comment: string | null; - created_at: Date; - updated_at: Date; -} - // Converts database names (snake_case) to GraphQL names (camelCase). function toWine(row: WineRow) { return { - id: String(row.id), - name: row.name, - type: row.type, - elaborate: row.elaborate, - grapes: row.grapes, - harmonize: row.harmonize, - abv: row.abv === null ? null : Number(row.abv), - body: row.body, - acidity: row.acidity, - countryCode: row.country_code, - country: row.country, - regionName: row.region_name, - wineryName: row.winery_name, - website: row.website, - vintages: row.vintages, - communityRating: row.community_avg === null ? null : Number(row.community_avg), - communityRatingCount: row.community_count, + id: String(row.id), + name: row.name, + type: row.type, + elaborate: row.elaborate, + grapes: row.grapes, + harmonize: row.harmonize, + abv: row.abv === null ? null : Number(row.abv), + body: row.body, + acidity: row.acidity, + countryCode: row.country_code, + country: row.country, + regionName: row.region_name, + wineryName: row.winery_name, + website: row.website, + vintages: row.vintages, + communityRating: row.community_avg === null ? null : Number(row.community_avg), + communityRatingCount: row.community_count, }; } -// The user ID is left out on purpose, so it is never sent to other users. +// The browser's UUID is not in the review table at all, so it can never be sent to other users. function toReview(row: ReviewRow) { return { - id: String(row.id), - wineId: row.wine_id, - rating: row.rating, - comment: row.comment, - author: authorName(row.user_id), - createdAt: row.created_at.toISOString(), - updatedAt: row.updated_at.toISOString(), + id: String(row.id), + wineId: row.wine_id, + rating: row.rating, + comment: row.comment, + author: authorName(row.student_id), + createdAt: row.created_at.toISOString(), + updatedAt: row.updated_at.toISOString(), }; } @@ -102,120 +71,127 @@ async function filterOptions( export const resolvers = { Query: { - async wines(_parent: unknown, args: WinesArgs) { - const query = buildWinesQuery(args); - const [list, count] = await Promise.all([ - pool.query(query.listSql, query.listParams), - pool.query<{ total: number }>(query.countSql, query.countParams), - ]); - - const rows = list.rows.slice(0, query.first); - const edges = rows.map((row, i) => ({ - cursor: encodeCursor(query.offset + i + 1), - node: toWine(row), - })); - - return { - totalCount: count.rows[0].total, - edges, - pageInfo: { - hasNextPage: list.rows.length > query.first, - endCursor: edges.at(-1)?.cursor ?? null, + async wines(_parent: unknown, args: WinesArgs) { + const query = buildWinesQuery(args); + const [list, count] = await Promise.all([ + pool.query(query.listSql, query.listParams), + pool.query<{ total: number }>(query.countSql, query.countParams), + ]); + + const rows = list.rows.slice(0, query.first); + const edges = rows.map((row, i) => ({ + cursor: encodeCursor(query.offset + i + 1), + node: toWine(row), + })); + + return { + totalCount: count.rows[0].total, + edges, + pageInfo: { + hasNextPage: list.rows.length > query.first, + endCursor: edges.at(-1)?.cursor ?? null, + }, + }; }, - }; - }, - async wine(_parent: unknown, args: { id: string }) { - const id = Number(args.id); - if (!Number.isInteger(id)) return null; - const result = await pool.query('SELECT * FROM wine WHERE id = $1', [id]); - return result.rows[0] ? toWine(result.rows[0]) : null; - }, + async wine(_parent: unknown, args: { id: string }) { + const id = Number(args.id); + if (!Number.isInteger(id)) return null; + const result = await pool.query('SELECT * FROM wine WHERE id = $1', [id]); + return result.rows[0] ? toWine(result.rows[0]) : null; + }, - // The counts are in the fields below, so a query only pays for the groups it asks for. - filterOptions(_parent: unknown, args: FilterArgs) { - return args; - }, + // The counts are in the fields below, so a query only pays for the groups it asks for. + filterOptions(_parent: unknown, args: FilterArgs) { + return args; + }, - async recentReviews(_parent: unknown, args: { first?: number | null }) { - const result = await pool.query( - 'SELECT * FROM review ORDER BY created_at DESC, id DESC LIMIT $1', - [limitReviews(args.first, 5)], - ); - return result.rows.map(toReview); - }, + async recentReviews(_parent: unknown, args: { first?: number | null }) { + const result = await pool.query( + 'SELECT * FROM review ORDER BY created_at DESC, id DESC LIMIT $1', + [limitReviews(args.first, 5)], + ); + return result.rows.map(toReview); + }, - async myReview(_parent: unknown, args: { wineId: string; userId: string }) { - const result = await pool.query( - 'SELECT * FROM review WHERE wine_id = $1 AND user_id = $2', - [validateWineId(args.wineId), validateUserId(args.userId)], - ); - return result.rows[0] ? toReview(result.rows[0]) : null; - }, + async myReview(_parent: unknown, args: { wineId: string; userId: string }) { + const result = await pool.query( + `SELECT review.* + FROM review + JOIN student ON student.id = review.student_id + WHERE review.wine_id = $1 AND student.user_id = $2`, + [validateWineId(args.wineId), validateUserId(args.userId)], + ); + return result.rows[0] ? toReview(result.rows[0]) : null; + }, }, Mutation: { - async saveReview(_parent: unknown, args: { input: ReviewInput }) { - const review = validateReviewInput(args.input); - try { - // Adds the review, or updates the old one if this user has already reviewed the wine. - const result = await pool.query( - `INSERT INTO review (wine_id, user_id, rating, comment) - VALUES ($1, $2, $3, $4) - ON CONFLICT (wine_id, user_id) - DO UPDATE SET rating = EXCLUDED.rating, comment = EXCLUDED.comment, updated_at = now() - RETURNING *`, - [review.wineId, review.userId, review.rating, review.comment], - ); - return toReview(result.rows[0]); - } catch (error) { - // 23503 = foreign key violation: the wine does not exist. - if ((error as { code?: string }).code === '23503') { - throw new GraphQLError('Wine not found.', { extensions: { code: 'BAD_USER_INPUT' } }); - } - throw error; - } - }, + async saveReview(_parent: unknown, args: { input: ReviewInput }) { + const review = validateReviewInput(args.input); + try { + // One statement: finds or creates the student, then adds the review or updates the old one. + // If the wine does not exist, nothing is saved, not even the student. + const result = await pool.query( + `WITH found_student AS ( + INSERT INTO student (user_id) VALUES ($2) + ON CONFLICT (user_id) DO UPDATE SET user_id = EXCLUDED.user_id + RETURNING id + ) + INSERT INTO review (wine_id, student_id, rating, comment) + SELECT $1, id, $3, $4 FROM found_student + ON CONFLICT (wine_id, student_id) + DO UPDATE SET rating = EXCLUDED.rating, comment = EXCLUDED.comment, updated_at = now() + RETURNING *`, + [review.wineId, review.userId, review.rating, review.comment], + ); + return toReview(result.rows[0]); + } catch (error) { + // 23503 = foreign key violation: the wine does not exist. + if ((error as { code?: string }).code === '23503') { + throw new GraphQLError('Wine not found.', { extensions: { code: 'BAD_USER_INPUT' } }); + } + throw error; + } + }, - async deleteReview(_parent: unknown, args: { wineId: string; userId: string }) { - const result = await pool.query( - 'DELETE FROM review WHERE wine_id = $1 AND user_id = $2', - [validateWineId(args.wineId), validateUserId(args.userId)], - ); - return (result.rowCount ?? 0) > 0; - }, + async deleteReview(_parent: unknown, args: { wineId: string; userId: string }) { + const result = await pool.query( + `DELETE FROM review + USING student + WHERE review.student_id = student.id AND review.wine_id = $1 AND student.user_id = $2`, + [validateWineId(args.wineId), validateUserId(args.userId)], + ); + return (result.rowCount ?? 0) > 0; + }, }, FilterOptions: { - types: (args: FilterArgs) => filterOptions(args, 'types'), - countries: (args: FilterArgs) => filterOptions(args, 'countries'), - grapes: (args: FilterArgs) => filterOptions(args, 'grapes'), - harmonize: (args: FilterArgs) => filterOptions(args, 'harmonize'), + types: (args: FilterArgs) => filterOptions(args, 'types'), + countries: (args: FilterArgs) => filterOptions(args, 'countries'), + grapes: (args: FilterArgs) => filterOptions(args, 'grapes'), + harmonize: (args: FilterArgs) => filterOptions(args, 'harmonize'), }, - // Fields on Wine that are not columns in the wine table. They only run when the frontend asks for them. + // Fields on Wine that are not columns in the wine table. The loaders batch them, + // so a page of 50 wines runs one query per field instead of 50. Wine: { - async studentRating(wine: { id: string }) { - const result = await pool.query<{ average: number | null; count: number }>( - 'SELECT AVG(rating)::float AS average, COUNT(*)::int AS count FROM review WHERE wine_id = $1', - [Number(wine.id)], - ); - return result.rows[0]; - }, + studentRating(wine: { id: string }, _args: unknown, { loaders }: Context) { + return loaders.studentRatings.load(Number(wine.id)); + }, - async reviews(wine: { id: string }, args: { first?: number | null }) { - const result = await pool.query( - 'SELECT * FROM review WHERE wine_id = $1 ORDER BY updated_at DESC, id DESC LIMIT $2', - [Number(wine.id), limitReviews(args.first, 10)], - ); - return result.rows.map(toReview); - }, + async reviews(wine: { id: string }, args: { first?: number | null }, { loaders }: Context) { + const rows = await loaders.reviews(limitReviews(args.first, 10)).load(Number(wine.id)); + return rows.map(toReview); + }, }, Review: { - async wine(review: { wineId: number }) { - const result = await pool.query('SELECT * FROM wine WHERE id = $1', [review.wineId]); - return toWine(result.rows[0]); - }, + async wine(review: { wineId: number }, _args: unknown, { loaders }: Context) { + const row = await loaders.wines.load(review.wineId); + // The foreign key should make this impossible, but a clear error is better than a crash. + if (!row) throw new GraphQLError('Wine not found.', { extensions: { code: 'NOT_FOUND' } }); + return toWine(row); + }, }, }; \ No newline at end of file diff --git a/backend/src/review-input.test.ts b/backend/src/review-input.test.ts index fcaf361..8c33551 100644 --- a/backend/src/review-input.test.ts +++ b/backend/src/review-input.test.ts @@ -56,13 +56,11 @@ describe('validateReviewInput', () => { }); describe('authorName', () => { - it('gives the same name for the same user', () => { - expect(authorName(USER_ID)).toBe(authorName(USER_ID)); + it('shows the student number', () => { + expect(authorName(4821)).toBe('Student #4821'); }); - it('looks like "Student #" and four digits, and never shows the ID', () => { - const name = authorName(USER_ID); - expect(name).toMatch(/^Student #\d{4}$/); - expect(name).not.toContain(USER_ID.slice(0, 8)); + it('gives different students different names', () => { + expect(authorName(1)).not.toBe(authorName(2)); }); }); \ No newline at end of file diff --git a/backend/src/review-input.ts b/backend/src/review-input.ts index d038ee6..aefff52 100644 --- a/backend/src/review-input.ts +++ b/backend/src/review-input.ts @@ -56,8 +56,7 @@ export function validateReviewInput(input: ReviewInput): ValidReview { }; } -/** A stable display name made from the anonymous ID, e.g. "Student #4821". The ID itself is never shown. */ -export function authorName(userId: string): string { - const number = (parseInt(userId.replace(/-/g, '').slice(0, 8), 16) % 9000) + 1000; - return `Student #${number}`; +/** The display name, e.g. "Student #4821". Built from the student number, so it is unique. The UUID is never shown. */ +export function authorName(studentId: number): string { + return `Student #${studentId}`; } \ No newline at end of file diff --git a/backend/src/server.ts b/backend/src/server.ts index 57e6267..409b828 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -2,6 +2,7 @@ import { ApolloServer } from '@apollo/server'; import { expressMiddleware } from '@as-integrations/express5'; import express from 'express'; import { pool } from './db'; +import { createLoaders, type Context } from './loaders'; import { resolvers } from './resolvers'; import { typeDefs } from './schema'; @@ -9,30 +10,35 @@ const PORT = Number(process.env.PORT ?? 3001); async function main() { const app = express(); - const apollo = new ApolloServer({ typeDefs, resolvers }); + const apollo = new ApolloServer({ typeDefs, resolvers }); await apollo.start(); - // Database check, same as before: shows that the backend can reach PostgreSQL. + // Database check, same as before: shows that the backend can reach PostgreSQL. app.get('/', async (_req, res) => { - try { - const { rows } = await pool.query( - 'SELECT current_database() AS database, current_user AS username, now() AS time', - ); - const info = rows[0]; - res.type('text').send( - `Hello from PostgreSQL!\nDatabase: ${info.database}\nUser: ${info.username}\nServer time: ${info.time.toISOString()}\n`, - ); - } catch (error) { - console.error('Database query failed:', error instanceof Error ? error.message : error); - res.status(503).type('text').send('Database unavailable\n'); - } + try { + const { rows } = await pool.query( + 'SELECT current_database() AS database, current_user AS username, now() AS time', + ); + const info = rows[0]; + res.type('text').send( + `Hello from PostgreSQL!\nDatabase: ${info.database}\nUser: ${info.username}\nServer time: ${info.time.toISOString()}\n`, + ); + } catch (error) { + console.error('Database query failed:', error instanceof Error ? error.message : error); + res.status(503).type('text').send('Database unavailable\n'); + } }); - app.use('/graphql', express.json(), expressMiddleware(apollo)); + // Fresh loaders for every request, so batched data is never shared between requests. + app.use( + '/graphql', + express.json(), + expressMiddleware(apollo, { context: async () => ({ loaders: createLoaders() }) }), + ); app.listen(PORT, () => { - console.log(`Backend listening on http://localhost:${PORT}`); - console.log(`GraphQL: http://localhost:${PORT}/graphql`); + console.log(`Backend listening on http://localhost:${PORT}`); + console.log(`GraphQL: http://localhost:${PORT}/graphql`); }); } diff --git a/docs/api.md b/docs/api.md index 3e20453..8558382 100644 --- a/docs/api.md +++ b/docs/api.md @@ -59,7 +59,7 @@ During development, Vite forwards `/graphql` to the backend. On the VM, Apache f A review is a die roll from 1 to 6 and an optional comment (max 500 characters). There is no login yet, so the frontend creates a random UUID once (`crypto.randomUUID()`), stores it in localStorage and sends it as `userId`. Treat it like a password: the API never -returns it, and reviews are shown with a display name such as "Student #8086". +returns it, reviews are shown with a display name such as "Student #12". Every student gets their own number the first time they save a review, so two students never share a name. Each user has one review per wine. Saving again replaces the old review, including the comment. @@ -90,4 +90,6 @@ mutation DeleteReview($wineId: ID!, $userId: ID!) { Invalid input (a rating outside 1–6, a too long comment, an unknown wine) gives an error with the code `BAD_USER_INPUT` and a message that can be shown to the user. -`first` is limited to 50. \ No newline at end of file +`first` is limited to 50. + +`studentRating`, `reviews` and `Review.wine` are loaded in batches with DataLoader, so a page of wines runs one query per field instead of one per wine. \ No newline at end of file From 49b0b5b78842c076e2c628125b46ffa0444d5118 Mon Sep 17 00:00:00 2001 From: SivertEikrem Date: Wed, 11 Nov 2026 14:29:38 +0100 Subject: [PATCH 4/4] fix(backend): use a 1-5 scale for student reviews (#33) --- backend/migrations/1794333349979_create-review-table.sql | 2 +- backend/src/review-input.test.ts | 8 ++++---- backend/src/review-input.ts | 2 +- backend/src/schema.ts | 2 +- docs/api.md | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/backend/migrations/1794333349979_create-review-table.sql b/backend/migrations/1794333349979_create-review-table.sql index 469df2c..32f1a35 100644 --- a/backend/migrations/1794333349979_create-review-table.sql +++ b/backend/migrations/1794333349979_create-review-table.sql @@ -12,7 +12,7 @@ CREATE TABLE review ( id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, wine_id integer NOT NULL REFERENCES wine (id) ON DELETE CASCADE, student_id integer NOT NULL REFERENCES student (id) ON DELETE CASCADE, - rating smallint NOT NULL CHECK (rating BETWEEN 1 AND 6), -- die roll + rating smallint NOT NULL CHECK (rating BETWEEN 1 AND 5), comment text CHECK (char_length(comment) <= 500), created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), diff --git a/backend/src/review-input.test.ts b/backend/src/review-input.test.ts index 8c33551..968f530 100644 --- a/backend/src/review-input.test.ts +++ b/backend/src/review-input.test.ts @@ -9,14 +9,14 @@ describe('validateReviewInput', () => { expect(review).toEqual({ wineId: 100062, userId: USER_ID, rating: 5, comment: 'Godt!' }); }); - it('accepts every side of the die', () => { - for (const rating of [1, 2, 3, 4, 5, 6]) { + it('accepts', () => { + for (const rating of [1, 2, 3, 4, 5]) { expect(validateReviewInput({ wineId: '1', userId: USER_ID, rating }).rating).toBe(rating); } }); - it('rejects ratings outside the die and half values', () => { - for (const rating of [0, 7, -1, 3.5]) { + it('rejects ratings outside the range and half values', () => { + for (const rating of [0, 6, -1, 3.5]) { expect(() => validateReviewInput({ wineId: '1', userId: USER_ID, rating })).toThrow('rating'); } }); diff --git a/backend/src/review-input.ts b/backend/src/review-input.ts index aefff52..8a995ba 100644 --- a/backend/src/review-input.ts +++ b/backend/src/review-input.ts @@ -2,7 +2,7 @@ import { GraphQLError } from 'graphql'; export const MIN_RATING = 1; -export const MAX_RATING = 6; // Die roll. Change together with the CHECK in the review migration. +export const MAX_RATING = 5; // Die roll. Change together with the CHECK in the review migration. export const MAX_COMMENT_LENGTH = 500; export interface ReviewInput { diff --git a/backend/src/schema.ts b/backend/src/schema.ts index 2751422..5f8cf93 100644 --- a/backend/src/schema.ts +++ b/backend/src/schema.ts @@ -86,7 +86,7 @@ export const typeDefs = `#graphql type Review { id: ID! - "Die roll from 1 to 6." + "Rating 0 to 5." rating: Int! comment: String "Display name such as 'Student #4821'. The user ID is never shown." diff --git a/docs/api.md b/docs/api.md index 8558382..43ae1b2 100644 --- a/docs/api.md +++ b/docs/api.md @@ -88,7 +88,7 @@ mutation DeleteReview($wineId: ID!, $userId: ID!) { } ``` -Invalid input (a rating outside 1–6, a too long comment, an unknown wine) gives an error +Invalid input (a rating outside 1–5, a too long comment, an unknown wine) gives an error with the code `BAD_USER_INPUT` and a message that can be shown to the user. `first` is limited to 50.