diff --git a/README.md b/README.md index 9ebb608..23d718c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Kork & Krone -**Last updated:** 17 November 2026 +**Last updated:** 18 November 2026 **Submission:** 4 (working system, ready for feedback on every aspect) **Status:** In progress. See [Status for submission 4](#status-for-submission-4). @@ -24,7 +24,7 @@ Students can search, filter and sort a catalogue of wines. Each wine shows one a ## Contents 1. [Status for submission 4](#status-for-submission-4) -2. [Get started](#get-started) +2. [Get started](#get-started) (and the [demo user](#demo-user)) 3. [Features](#features) 4. [Architecture and technology choices](#architecture-and-technology-choices) 5. [Data](#data) @@ -59,6 +59,8 @@ yet, depending on when the review is made. | «Mine anmeldelser» page | Done | Shows the «Vil prøve» list. Own reviews come with login in the interface | | User accounts | Done | Register, log in and log out at `/konto`, with sessions in PostgreSQL and an `httpOnly` cookie | | Reviews tied to accounts | Done | Writing a review requires login, and the username is shown as the author. Older anonymous reviews are kept as «Anonym student» | +| Favourites, top 4, «Vil prøve» and «Har prøvd» per user | Backend done | API and rules in [API](docs/api.md#wine-lists). The interface comes next | +| Demo user for testing | Done | `demo` / `kork-og-krone`, see [Demo user](#demo-user) | | Larger dataset on the VM | Done | Full version: 100 646 wines and 21 013 536 ratings | | Continuous integration (CI) | Not yet started | Needs a self-hosted runner | @@ -83,6 +85,7 @@ npm ci --prefix frontend cp backend/.env.example backend/.env # then set your database password npm run db:migrate --prefix backend npm run db:seed:test --prefix backend +npm run db:seed:demo --prefix backend # the demo user below ``` Start the backend and the frontend in two terminals: @@ -96,6 +99,19 @@ The landing page needs the backend for wines and categories. Without it, the pag To deploy on the VM, see the [VM guide](docs/vm.md). +### Demo user + +To try the features that need login without registering, log in at `/konto` with: + +| Username | Password | +|---|---| +| `demo` | `kork-og-krone` | + +The user has favourites with a top 4, wines on «Vil prøve» and «Har prøvd», and some reviews. It exists +on the VM, and locally after `npm run db:seed:demo`, which also resets it if someone has changed it. +Everyone can see the password, so do not store anything private on this user. Searching and reading +reviews never require login. + ## Features This section describes what users can do. "Backend" means the API supports the feature. "UI" means it is visible on the site. @@ -110,7 +126,8 @@ This section describes what users can do. "Backend" means the API supports the f | Wine detail page | Done (`wine(id)`) | Done | Name, winery, region, grapes, alcohol, body, acidity, vintages and food pairing in Norwegian. Grapes and food link to the search | | Student reviews | Done | Done | 0.5–5 stars in half stars and an optional comment, stored in PostgreSQL. Hover the left half of a star for half a star, or use the arrow keys. The page updates at once without a reload. One review per student per wine | | Shared average and distribution | Done | Done | Student reviews count in the average together with X-Wines, also when sorting and filtering. The wine page shows how many gave each score | -| Wishlist ("Vil prøve") | Planned | Done | Saved in the browser and shown on «Mine anmeldelser». Moves to the backend when login is in the interface | +| Wishlist ("Vil prøve") | Done | Done | Saved in the browser and shown on «Mine anmeldelser». The interface moves to the backend list next | +| Favourites, top 4 and «Har prøvd» | Done | Planned | Stored per user and public. «Har prøvd» takes a wine off «Vil prøve», and a saved review marks the wine as tried. See [API](docs/api.md#wine-lists) | | User accounts | Done | Done | Register, log in and log out at `/konto`. Errors are shown next to the field they are about, in Norwegian. Sessions in PostgreSQL with an `httpOnly` cookie | | Reviews with login | Done | Done | Only logged-in users can write, change or delete a review, and only their own. Visitors see the reviews and a link to log in, which brings them back to the wine. `User.reviews` lists a user's reviews for the profile page | @@ -284,7 +301,7 @@ and because the test was run over VPN. These are the "before" numbers. Compressi | Unit and components (frontend) | Vitest, React Testing Library, user-event, vitest-axe | URL parameters, formatting, mapping of API data, data hooks, components, the landing page, the wine page with reviews, the wishlist page, loading, empty and error states, and axe on each component | 269 in 28 files | | Unit (backend) | Vitest | Parsing of X-Wines CSV files, building SQL for search, filtering and sorting, review validation, and passwords, sessions and rate limiting | 92 in 11 files (6 skipped: they need a test database) | | End-to-end | Playwright with axe-core, desktop and mobile | Landing, search and detail pages with a stubbed API: one request per page load, debounce, search, filters, sorting, load more, reload, back button, from search to wine and back, the filter dialog on mobile, no hits, wine not found, API errors, keyboard use, reflow at 320 px, and no axe violations (WCAG 2.1 AA) | 50 (24 tests in 2 browser projects, and 2 for mobile only) | -| API | Vitest with Apollo Server (`executeOperation`) | Login and reviews through real GraphQL requests, with a fake browser per user that keeps the cookie. The review tests run against a separate test database (`TEST_DATABASE_URL`), see [API](docs/api.md#database-tests) | Count again | +| API | Vitest with Apollo Server (`executeOperation`) | Login, reviews, wine lists, the top 4 and the demo user through real GraphQL requests, with a fake browser per user that keeps the cookie. The review tests run against a separate test database (`TEST_DATABASE_URL`), see [API](docs/api.md#database-tests) | Count again | Counted on 16 November 2026. The skipped backend tests run the user store against a real database, and need `TEST_DATABASE_URL`. @@ -374,9 +391,10 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a ### Next: towards the final submission - [x] Login in the interface: forms for register and login, and reviews tied to the account instead of the anonymous ID. -- [ ] Favourites with a top 4, «Vil prøve» and «Har prøvd» stored per user. +- [x] Favourites with a top 4, «Vil prøve» and «Har prøvd» stored per user (backend and API). +- [ ] The lists in the interface: heart, bookmark and «Har prøvd» on the wines. - [ ] Profile page with the top 4, the lists and the user's reviews. -- [ ] Wishlist stored in the backend, so it follows the user between devices. +- [ ] Wishlist stored in the backend, so it follows the user between devices. The API is ready. - [ ] Calmer landing page: less text, a separate «Om» page, and a burger menu on mobile. - [ ] CI, an enforced coverage threshold, and eslint-plugin-jsx-a11y. - [ ] Measure sustainability and fill in the budget table. @@ -411,8 +429,8 @@ Remove known issues as they are fixed. - [Setup](docs/setup.md): Git, dependencies, `.env` and local start - [Database](docs/database.md): PostgreSQL on macOS, Windows and Ubuntu - [VM](docs/vm.md): deployment, Apache and running the backend with `nohup` -- [API](docs/api.md): GraphQL queries, user accounts, reviews, database tests and the X-Wines citation -- [Manual testing](docs/manual-testing.md): how to test login, reviews and other user data by hand +- [API](docs/api.md): GraphQL queries, user accounts, reviews, wine lists, the demo user, database tests and the X-Wines citation +- [Manual testing](docs/manual-testing.md): how to test login, reviews, wine lists and the demo user by hand - [Screen reader testing](docs/screen-reader.md): what we found, what we fixed and the VoiceOver script - [Workflow](docs/workflow.md): branches, reviews and checks - [Tasks](docs/tasks.md): requirements and sketches \ No newline at end of file diff --git a/backend/migrations/1794998259977_review-user-index-by-id.sql b/backend/migrations/1794998259977_review-user-index-by-id.sql new file mode 100644 index 0000000..00e4182 --- /dev/null +++ b/backend/migrations/1794998259977_review-user-index-by-id.sql @@ -0,0 +1,11 @@ +-- Up Migration + +-- A user's reviews are now listed by id, newest first, so an edit does not move a review while +-- someone pages through the list. The index follows the new ORDER BY (user_id, id DESC). +DROP INDEX review_user_updated; +CREATE INDEX review_user_id ON review (user_id, id DESC); + +-- Down Migration + +DROP INDEX review_user_id; +CREATE INDEX review_user_updated ON review (user_id, updated_at DESC); diff --git a/backend/migrations/1794998971543_create-user-wine.sql b/backend/migrations/1794998971543_create-user-wine.sql new file mode 100644 index 0000000..09a89cb --- /dev/null +++ b/backend/migrations/1794998971543_create-user-wine.sql @@ -0,0 +1,35 @@ +-- Up Migration + +-- A user's wine lists: favourites, «Vil prøve» and «Har prøvd». One row per wine per list. +-- All lists are public on the profile, so nothing here is secret. +CREATE TABLE user_wine ( + -- Used to sort a list (newest first) and as the page cursor, like review.id. + -- An id never changes, so paging is stable while the list changes. + id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + user_id integer NOT NULL REFERENCES app_user (id) ON DELETE CASCADE, + wine_id integer NOT NULL REFERENCES wine (id) ON DELETE CASCADE, + -- Text with a CHECK instead of an enum type: a new list is one more value here, in a plain + -- migration. The values are the GraphQL enum WineList, and must be changed together with it. + list text NOT NULL CHECK (list IN ('FAVOURITE', 'WANT_TO_TRY', 'TRIED')), + added_at timestamptz NOT NULL DEFAULT now(), + -- 1-4 for the favourites chosen for the top of the profile, otherwise null. + top_position smallint CHECK (top_position BETWEEN 1 AND 4), + + -- A wine is on each list at most once. + CONSTRAINT user_wine_once UNIQUE (user_id, list, wine_id), + -- Only favourites can be in the top 4. Removing a favourite removes it from the top 4 too. + CONSTRAINT user_wine_top_only_favourites CHECK (top_position IS NULL OR list = 'FAVOURITE') +); + +-- Each place in the top 4 holds one wine. +CREATE UNIQUE INDEX user_wine_top ON user_wine (user_id, top_position) WHERE top_position IS NOT NULL; + +-- One list for a user, newest first, page by page (User.wines). +CREATE INDEX user_wine_list_newest ON user_wine (user_id, list, id DESC); + +-- Which lists a page of wines is on for one user (Wine.myLists). +CREATE INDEX user_wine_user_wine ON user_wine (user_id, wine_id); + +-- Down Migration + +DROP TABLE user_wine; diff --git a/backend/package.json b/backend/package.json index 65f6a1c..82e93f2 100644 --- a/backend/package.json +++ b/backend/package.json @@ -12,6 +12,7 @@ "typecheck": "tsc --noEmit", "test": "vitest run", "db:seed:test": "tsx src/scripts/seed-xwines.ts data/xwines-test/wines.csv data/xwines-test/ratings.csv", + "db:seed:demo": "tsx src/scripts/seed-demo-user.ts", "db:migrate": "node-pg-migrate up", "db:migrate:down": "node-pg-migrate down", "db:migrate:create": "node-pg-migrate create --migration-file-language sql" diff --git a/backend/src/connection.test.ts b/backend/src/connection.test.ts new file mode 100644 index 0000000..e754692 --- /dev/null +++ b/backend/src/connection.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest'; +import { decodeIdCursor, encodeIdCursor, toConnection } from './connection'; + +describe('toConnection', () => { + const page = (rows: number[], first: number) => + toConnection({ + rows, + first, + totalCount: 10, + toNode: (row) => ({ id: row }), + cursorFor: (row) => encodeIdCursor(row), + }); + + it('uses the extra row only to tell that there is a next page', () => { + const result = page([9, 8, 7], 2); + expect(result.edges.map((edge) => edge.node.id)).toEqual([9, 8]); + expect(result.pageInfo).toEqual({ hasNextPage: true, endCursor: encodeIdCursor(8) }); + expect(result.totalCount).toBe(10); + }); + + it('has no next page and no end cursor when the page is empty', () => { + expect(page([], 2).pageInfo).toEqual({ hasNextPage: false, endCursor: null }); + }); +}); + +describe('id cursors', () => { + it('round-trips an id', () => { + expect(decodeIdCursor(encodeIdCursor(4821))).toBe(4821); + expect(decodeIdCursor(encodeIdCursor(2_147_483_647))).toBe(2_147_483_647); + expect(decodeIdCursor(null)).toBeNull(); + expect(decodeIdCursor(undefined)).toBeNull(); + }); + + it.each([ + ['not base64 at all', 'not-a-cursor'], + ['an offset cursor', Buffer.from('offset:10').toString('base64')], + ['a negative id', Buffer.from('id:-1').toString('base64')], + ['id 0', Buffer.from('id:0').toString('base64')], + ['an id above the largest database integer', Buffer.from('id:2147483648').toString('base64')], + ['a very long number', Buffer.from(`id:${'9'.repeat(25)}`).toString('base64')], + ])('rejects %s with BAD_USER_INPUT', (_name, cursor) => { + expect(() => decodeIdCursor(cursor)).toThrow( + expect.objectContaining({ extensions: { code: 'BAD_USER_INPUT' } }), + ); + }); +}); diff --git a/backend/src/connection.ts b/backend/src/connection.ts new file mode 100644 index 0000000..ac97bac --- /dev/null +++ b/backend/src/connection.ts @@ -0,0 +1,57 @@ +// Pages in the GraphQL connection format ({ totalCount, edges, pageInfo }), shared by the wine +// search, a user's reviews and a user's wine lists. +import { GraphQLError } from 'graphql'; + +/** + * A page from `rows`, which holds one row more than `first` when there is a next page. + * That extra row is only used to set hasNextPage. + */ +export function toConnection({ + rows, + first, + totalCount, + toNode, + cursorFor, +}: { + rows: Row[]; + first: number; + totalCount: number; + toNode: (row: Row) => Node; + /** The cursor that points just after this row. `index` is its place on the page. */ + cursorFor: (row: Row, index: number) => string; +}) { + const edges = rows.slice(0, first).map((row, index) => ({ + cursor: cursorFor(row, index), + node: toNode(row), + })); + return { + totalCount, + edges, + pageInfo: { hasNextPage: rows.length > first, endCursor: edges.at(-1)?.cursor ?? null }, + }; +} + +/* + * Cursors for lists that belong to a user (reviews, wine lists). They hold the id of the last row + * on the page, and the next page asks for ids below it ("keyset pagination"). Rows are sorted by + * id, newest first, and an id never changes, so a row that is edited while someone is paging is + * neither skipped nor shown twice. An offset would move when rows are added or removed. + */ + +/** The largest value of a PostgreSQL `integer`. A larger id cannot exist, and the query would fail. */ +const MAX_INTEGER = 2_147_483_647; + +export function encodeIdCursor(id: number): string { + return Buffer.from(`id:${id}`).toString('base64'); +} + +/** The id in the cursor, or null without one. A cursor the API did not make gives BAD_USER_INPUT. */ +export function decodeIdCursor(cursor: string | null | undefined): number | null { + if (!cursor) return null; + const match = /^id:(\d{1,10})$/.exec(Buffer.from(cursor, 'base64').toString('utf8')); + const id = match ? Number(match[1]) : NaN; + if (!Number.isInteger(id) || id <= 0 || id > MAX_INTEGER) { + throw new GraphQLError('Invalid cursor.', { extensions: { code: 'BAD_USER_INPUT' } }); + } + return id; +} diff --git a/backend/src/db-errors.test.ts b/backend/src/db-errors.test.ts new file mode 100644 index 0000000..73bcc31 --- /dev/null +++ b/backend/src/db-errors.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest'; +import { isForeignKeyViolation } from './db-errors'; + +describe('isForeignKeyViolation', () => { + it('matches the code and the constraint name', () => { + const error = { code: '23503', constraint: 'review_wine_id_fkey' }; + expect(isForeignKeyViolation(error, 'review_wine_id_fkey')).toBe(true); + expect(isForeignKeyViolation(error, 'review_user_id_fkey')).toBe(false); + }); + + it('ignores other errors', () => { + expect(isForeignKeyViolation({ code: '23505', constraint: 'review_wine_id_fkey' }, 'review_wine_id_fkey')).toBe(false); + expect(isForeignKeyViolation(new Error('Connection lost'), 'review_wine_id_fkey')).toBe(false); + expect(isForeignKeyViolation(null, 'review_wine_id_fkey')).toBe(false); + }); +}); diff --git a/backend/src/db-errors.ts b/backend/src/db-errors.ts new file mode 100644 index 0000000..9c130bd --- /dev/null +++ b/backend/src/db-errors.ts @@ -0,0 +1,19 @@ +// Recognises PostgreSQL errors by code and constraint name, so a resolver can turn them into +// errors the frontend understands. Codes: https://www.postgresql.org/docs/current/errcodes-appendix.html + +const FOREIGN_KEY_VIOLATION = '23503'; + +interface PgError { + code?: unknown; + constraint?: unknown; +} + +/** + * True when `error` is a foreign key violation on the named constraint, for example + * `review_wine_id_fkey` when the wine does not exist. The name tells which reference failed, + * since one table can have several. + */ +export function isForeignKeyViolation(error: unknown, constraint: string): boolean { + const pgError = error as PgError | null; + return pgError?.code === FOREIGN_KEY_VIOLATION && pgError.constraint === constraint; +} diff --git a/backend/src/db.ts b/backend/src/db.ts index 7600ff5..49b3f68 100644 --- a/backend/src/db.ts +++ b/backend/src/db.ts @@ -1,6 +1,6 @@ import { existsSync } from 'node:fs'; import path from 'node:path'; -import { Pool } from 'pg'; +import { Pool, type PoolClient } from 'pg'; // Load backend/.env if it exists. Variables already set in the shell take priority. const envFile = path.join(__dirname, '..', '.env'); @@ -10,4 +10,23 @@ if (!process.env.DATABASE_URL) { throw new Error('DATABASE_URL is required. See docs/setup.md.'); } -export const pool = new Pool({ connectionString: process.env.DATABASE_URL }); \ No newline at end of file +export const pool = new Pool({ connectionString: process.env.DATABASE_URL }); + +/** + * Runs `work` in one transaction on one connection: either everything in it is saved, or + * nothing is. Use the `client` it gets, not `pool`, for every query that belongs to it. + */ +export async function withTransaction(work: (client: PoolClient) => Promise): Promise { + const client = await pool.connect(); + try { + await client.query('BEGIN'); + const result = await work(client); + await client.query('COMMIT'); + return result; + } catch (error) { + await client.query('ROLLBACK'); + throw error; + } finally { + client.release(); + } +} \ No newline at end of file diff --git a/backend/src/demo/demo-user.db.test.ts b/backend/src/demo/demo-user.db.test.ts new file mode 100644 index 0000000..5e0b820 --- /dev/null +++ b/backend/src/demo/demo-user.db.test.ts @@ -0,0 +1,106 @@ +// The demo user against the test database. Skipped unless TEST_DATABASE_URL is set. +import { afterAll, describe, expect, it } from 'vitest'; +import { verifyPassword } from '../auth/password'; +import { pool, withTransaction } from '../db'; +import { createTestApi } from '../test/graphql-test-api'; +import { DEMO_PASSWORD, DEMO_USERNAME, DEMO_WINE_COUNT, seedDemoUser } from './demo-user'; + +const url = process.env.TEST_DATABASE_URL; + +const FAST_SCRYPT = { N: 1024, r: 8, p: 1 }; + +describe.skipIf(!url)('demo user (PostgreSQL)', () => { + const api = createTestApi({ firstId: 700_000_000 }); + afterAll(async () => { + await pool.query('DELETE FROM app_user WHERE username = $1', [DEMO_USERNAME]); + await api.close(); + }); + + /** What the demo user has, read straight from the database. */ + async function stateOf(userId: number) { + const lists = await pool.query<{ list: string; wine_id: number; top_position: number | null }>( + 'SELECT list, wine_id, top_position FROM user_wine WHERE user_id = $1', + [userId], + ); + const reviews = await pool.query<{ wine_id: number }>('SELECT wine_id FROM review WHERE user_id = $1', [ + userId, + ]); + const on = (list: string) => lists.rows.filter((row) => row.list === list).map((row) => row.wine_id); + const top = lists.rows + .filter((row) => row.top_position !== null) + .sort((a, b) => (a.top_position ?? 0) - (b.top_position ?? 0)) + .map((row) => row.wine_id); + return { + favourites: on('FAVOURITE').sort((a, b) => a - b), + wantToTry: on('WANT_TO_TRY').sort((a, b) => a - b), + tried: on('TRIED').sort((a, b) => a - b), + top, + reviewed: reviews.rows.map((row) => row.wine_id).sort((a, b) => a - b), + }; + } + + it('creates a user with the documented password, lists that follow the rules, and reviews', async () => { + const wineIds = (await api.createWines(DEMO_WINE_COUNT)).map(Number); + + const { userId } = await withTransaction((client) => + seedDemoUser(client, { wineIds, scryptParams: FAST_SCRYPT }), + ); + + const user = await pool.query<{ password_hash: string }>('SELECT password_hash FROM app_user WHERE id = $1', [ + userId, + ]); + expect(await verifyPassword(DEMO_PASSWORD, user.rows[0].password_hash)).toBe(true); + + const state = await stateOf(userId); + expect(state.favourites).toHaveLength(6); + expect(state.wantToTry).toHaveLength(5); + expect(state.top).toHaveLength(4); + expect(state.reviewed).toHaveLength(5); + // The rules: the top 4 are favourites, reviewed wines are tried, and tried wines are not on «Vil prøve». + expect(state.favourites).toEqual(expect.arrayContaining(state.top)); + expect(state.tried).toEqual(expect.arrayContaining(state.reviewed)); + expect(state.wantToTry.filter((wine) => state.tried.includes(wine))).toEqual([]); + + // The reviews count in the wines' averages. + const stats = await pool.query<{ community_count: number }>( + 'SELECT community_count FROM wine WHERE id = ANY($1)', + [state.reviewed], + ); + expect(stats.rows.map((row) => row.community_count)).toEqual([1, 1, 1, 1, 1]); + }); + + it('resets the same user to the same state when it is run again, also with other wines', async () => { + const firstWines = (await api.createWines(DEMO_WINE_COUNT)).map(Number); + const secondWines = (await api.createWines(DEMO_WINE_COUNT)).map(Number); + const seed = (wineIds: number[]) => + withTransaction((client) => seedDemoUser(client, { wineIds, scryptParams: FAST_SCRYPT })); + + const first = await seed(firstWines); + const before = await stateOf(first.userId); + expect((await seed(firstWines)).userId).toBe(first.userId); + expect(await stateOf(first.userId)).toEqual(before); + + // With other wines (a new import), nothing is left of the old ones, and their averages are updated. + await seed(secondWines); + const after = await stateOf(first.userId); + const listed = [...after.favourites, ...after.wantToTry, ...after.tried]; + expect(listed.filter((wine) => !secondWines.includes(wine))).toEqual([]); + const old = await pool.query<{ community_count: number }>( + 'SELECT community_count FROM wine WHERE id = ANY($1)', + [before.reviewed], + ); + expect(old.rows.map((row) => row.community_count)).toEqual([0, 0, 0, 0, 0]); + }); + + it('refuses too few wines or the same wine twice, and changes nothing', async () => { + const wineIds = (await api.createWines(DEMO_WINE_COUNT - 1)).map(Number); + await expect( + withTransaction((client) => seedDemoUser(client, { wineIds, scryptParams: FAST_SCRYPT })), + ).rejects.toThrow(`needs ${DEMO_WINE_COUNT} different wines`); + await expect( + withTransaction((client) => + seedDemoUser(client, { wineIds: [...wineIds, wineIds[0]], scryptParams: FAST_SCRYPT }), + ), + ).rejects.toThrow(`needs ${DEMO_WINE_COUNT} different wines`); + }); +}); diff --git a/backend/src/demo/demo-user.ts b/backend/src/demo/demo-user.ts new file mode 100644 index 0000000..0fe3e48 --- /dev/null +++ b/backend/src/demo/demo-user.ts @@ -0,0 +1,88 @@ +// The demo user for the evaluation: a known username and password, with favourites, a top 4, +// the other lists and some reviews, so the profile features can be tried without typing in +// data first. The password is public (README), so the account must never hold anything private. +// +// Running it again resets the user to the same state: its lists and reviews are replaced. +import type { PoolClient } from 'pg'; +import { DEFAULT_SCRYPT_PARAMS, hashPassword, type ScryptParams } from '../auth/password'; +import { setTopFavourites, setWineInList, type WineList } from '../lists/wine-lists'; +import { UPDATE_WINE_RATING_STATS } from '../rating-stats'; + +export const DEMO_USERNAME = 'demo'; +export const DEMO_PASSWORD = 'kork-og-krone'; + +/** The reviews of the demo user, by the index of the wine in the list given to seedDemoUser. */ +const REVIEWS: { wine: number; rating: number; comment: string }[] = [ + { wine: 0, rating: 5, comment: 'Favoritten. Fyldig og rund, perfekt til lam.' }, + { wine: 1, rating: 4.5, comment: 'Mye smak for pengene. Kjøper igjen.' }, + { wine: 2, rating: 4, comment: 'Frisk og lett, god til fisk.' }, + { wine: 10, rating: 3, comment: 'Grei nok, men litt tynn.' }, + { wine: 11, rating: 2.5, comment: 'For søt for min smak.' }, +]; + +/** The lists, by wine index. The reviewed wines are put on «Har prøvd» by the reviews. */ +const LISTS: { list: WineList; wines: number[] }[] = [ + { list: 'FAVOURITE', wines: [0, 1, 2, 3, 4, 5] }, + { list: 'TRIED', wines: [3, 12] }, + { list: 'WANT_TO_TRY', wines: [6, 7, 8, 9, 13] }, +]; + +/** The top 4, by wine index: chosen among the favourites, not just the first four. */ +const TOP_FAVOURITES = [2, 0, 4, 1]; + +/** How many different wines seedDemoUser needs. */ +export const DEMO_WINE_COUNT = 14; + +/** + * Creates the demo user, or resets it, with the given wines. Runs in the caller's transaction. + * Uses the same functions as the API, so the demo data follows the same rules. + */ +export async function seedDemoUser( + client: PoolClient, + { wineIds, scryptParams = DEFAULT_SCRYPT_PARAMS }: { wineIds: number[]; scryptParams?: ScryptParams }, +): Promise<{ userId: number }> { + if (new Set(wineIds).size !== DEMO_WINE_COUNT || wineIds.length !== DEMO_WINE_COUNT) { + throw new Error(`The demo user needs ${DEMO_WINE_COUNT} different wines, got ${wineIds.length}.`); + } + + // Also resets the password, in case it was changed. + const passwordHash = await hashPassword(DEMO_PASSWORD, scryptParams); + const user = await client.query<{ id: number }>( + `INSERT INTO app_user (username, password_hash) VALUES ($1, $2) + ON CONFLICT (username) DO UPDATE SET password_hash = EXCLUDED.password_hash + RETURNING id`, + [DEMO_USERNAME, passwordHash], + ); + const userId = user.rows[0].id; + + // Start from nothing. The wines that lose a review need their average recalculated too. + const oldReviews = await client.query<{ wine_id: number }>( + 'DELETE FROM review WHERE user_id = $1 RETURNING wine_id', + [userId], + ); + await client.query('DELETE FROM user_wine WHERE user_id = $1', [userId]); + + for (const { list, wines } of LISTS) { + for (const index of wines) { + await setWineInList(client, { userId, wineId: wineIds[index], list, inList: true }); + } + } + for (const { wine, rating, comment } of REVIEWS) { + const wineId = wineIds[wine]; + await client.query('INSERT INTO review (wine_id, user_id, rating, comment) VALUES ($1, $2, $3, $4)', [ + wineId, + userId, + rating, + comment, + ]); + // The same rule as saveReview: a reviewed wine has been tried. + await setWineInList(client, { userId, wineId, list: 'TRIED', inList: true }); + } + await setTopFavourites(client, { userId, wineIds: TOP_FAVOURITES.map((index) => wineIds[index]) }); + + const reviewed = REVIEWS.map(({ wine }) => wineIds[wine]); + const changed = new Set([...oldReviews.rows.map((row) => row.wine_id), ...reviewed]); + for (const wineId of changed) await client.query(UPDATE_WINE_RATING_STATS, [wineId]); + + return { userId }; +} diff --git a/backend/src/graphql.ts b/backend/src/graphql.ts new file mode 100644 index 0000000..67b381e --- /dev/null +++ b/backend/src/graphql.ts @@ -0,0 +1,11 @@ +// The whole GraphQL API: every feature's types and resolvers. Apollo merges the lists. +// The server and the API tests both use this, so the tests run the same schema as the site. +import { authResolvers } from './auth/resolvers'; +import { authTypeDefs } from './auth/schema'; +import { listResolvers } from './lists/resolvers'; +import { listTypeDefs } from './lists/schema'; +import { resolvers } from './resolvers'; +import { typeDefs } from './schema'; + +export const allTypeDefs = [typeDefs, authTypeDefs, listTypeDefs]; +export const allResolvers = [resolvers, authResolvers, listResolvers]; diff --git a/backend/src/lists/lists-api.db.test.ts b/backend/src/lists/lists-api.db.test.ts new file mode 100644 index 0000000..91b8181 --- /dev/null +++ b/backend/src/lists/lists-api.db.test.ts @@ -0,0 +1,301 @@ +// API tests for the wine lists against the test database. +// Skipped unless TEST_DATABASE_URL is set. See "Database tests" in docs/api.md. +import { afterAll, describe, expect, it, vi } from 'vitest'; +import { pool } from '../db'; +import { codeOf, createTestApi, type GraphQLResult } from '../test/graphql-test-api'; + +const url = process.env.TEST_DATABASE_URL; + +const SET = `mutation Set($wineId: ID!, $list: WineList!, $inList: Boolean!) { + setWineInList(wineId: $wineId, list: $list, inList: $inList) { id myLists } +}`; +const MY_LISTS = `query MyLists($id: ID!) { wine(id: $id) { id myLists } }`; +const LIST = `query List($list: WineList!, $first: Int, $after: String) { + me { wines(list: $list, first: $first, after: $after) { + totalCount + edges { node { id } } + pageInfo { hasNextPage endCursor } + } } +}`; + +const SAVE_REVIEW = `mutation Save($input: ReviewInput!) { + saveReview(input: $input) { id wine { id myLists } } +}`; +const DELETE_REVIEW = `mutation Delete($wineId: ID!) { deleteReview(wineId: $wineId) }`; + +const SET_TOP = `mutation SetTop($wineIds: [ID!]!) { setTopFavourites(wineIds: $wineIds) { id topFavourites { id } } }`; +const TOP = `query Top { me { topFavourites { id } } }`; + +type Page = { totalCount: number; edges: { node: { id: string } }[]; pageInfo: { hasNextPage: boolean; endCursor: string | null } }; + +const listsOf = (result: GraphQLResult) => (result.data?.setWineInList ?? result.data?.wine) as { myLists: string[] }; +const pageOf = (result: GraphQLResult) => (result.data?.me as { wines: Page }).wines; +const idsOf = (page: Page) => page.edges.map((edge) => edge.node.id); +const topOf = (result: GraphQLResult) => { + const user = (result.data?.setTopFavourites ?? result.data?.me) as { topFavourites: { id: string }[] }; + return user.topFavourites.map((wine) => wine.id); +}; + +describe.skipIf(!url)('wine lists API (PostgreSQL)', () => { + const api = createTestApi({ firstId: 800_000_000 }); + afterAll(() => api.close()); + + const set = (wineId: string, list: string, inList = true) => ({ wineId, list, inList }); + + describe('without login', () => { + it('cannot change a list, and has no lists of its own', async () => { + const [wine] = await api.createWines(1); + const visitor = await api.createBrowser(); + expect(codeOf(await visitor.request(SET, set(wine, 'FAVOURITE')))).toBe('UNAUTHENTICATED'); + expect(listsOf(await visitor.request(MY_LISTS, { id: wine })).myLists).toEqual([]); + }); + }); + + describe('setWineInList', () => { + it('puts a wine on a list and takes it off again, and doing it twice changes nothing', async () => { + const [wine] = await api.createWines(1); + const kari = await api.createBrowser('kari'); + + expect(listsOf(await kari.request(SET, set(wine, 'FAVOURITE'))).myLists).toEqual(['FAVOURITE']); + expect(listsOf(await kari.request(SET, set(wine, 'FAVOURITE'))).myLists).toEqual(['FAVOURITE']); + expect(pageOf(await kari.request(LIST, { list: 'FAVOURITE' })).totalCount).toBe(1); + + expect(listsOf(await kari.request(SET, set(wine, 'FAVOURITE', false))).myLists).toEqual([]); + expect(listsOf(await kari.request(SET, set(wine, 'FAVOURITE', false))).myLists).toEqual([]); + }); + + it('lets a wine be on several lists, in a fixed order', async () => { + const [wine] = await api.createWines(1); + const ola = await api.createBrowser('ola'); + await ola.request(SET, set(wine, 'TRIED')); + const result = await ola.request(SET, set(wine, 'FAVOURITE')); + expect(listsOf(result).myLists).toEqual(['FAVOURITE', 'TRIED']); + }); + + it('takes a wine off «Vil prøve» when it goes on «Har prøvd»', async () => { + const [wine] = await api.createWines(1); + const per = await api.createBrowser('per'); + await per.request(SET, set(wine, 'WANT_TO_TRY')); + + const result = await per.request(SET, set(wine, 'TRIED')); + + expect(listsOf(result).myLists).toEqual(['TRIED']); + expect(pageOf(await per.request(LIST, { list: 'WANT_TO_TRY' })).totalCount).toBe(0); + }); + + it('keeps the lists of each user apart', async () => { + const [wine] = await api.createWines(1); + const anne = await api.createBrowser('anne'); + const tor = await api.createBrowser('tor'); + await anne.request(SET, set(wine, 'FAVOURITE')); + + expect(listsOf(await tor.request(MY_LISTS, { id: wine })).myLists).toEqual([]); + expect(pageOf(await tor.request(LIST, { list: 'FAVOURITE' })).totalCount).toBe(0); + }); + + it('rejects a wine that does not exist, and an unknown list', async () => { + const kim = await api.createBrowser('kim'); + expect(codeOf(await kim.request(SET, set('1999999999', 'FAVOURITE')))).toBe('BAD_USER_INPUT'); + expect(codeOf(await kim.request(SET, set('1', 'WISHLIST')))).toBe('BAD_USER_INPUT'); + }); + }); + + describe('User.wines', () => { + it('lists the newest first, one page at a time, without skipping when the list changes', async () => { + const [a, b, c] = await api.createWines(3); + const siv = await api.createBrowser('siv'); + for (const wine of [a, b, c]) await siv.request(SET, set(wine, 'WANT_TO_TRY')); + + const first = pageOf(await siv.request(LIST, { list: 'WANT_TO_TRY', first: 2 })); + expect(first.totalCount).toBe(3); + expect(idsOf(first)).toEqual([c, b]); + expect(first.pageInfo.hasNextPage).toBe(true); + + // A wine shown on the first page is taken off before the next page. With an offset, + // the next page would start one wine too late and skip «a». + await siv.request(SET, set(c, 'WANT_TO_TRY', false)); + + const second = pageOf( + await siv.request(LIST, { list: 'WANT_TO_TRY', first: 2, after: first.pageInfo.endCursor }), + ); + expect(idsOf(second)).toEqual([a]); + expect(second.pageInfo.hasNextPage).toBe(false); + }); + + it('rejects a cursor that was not made by the API', async () => { + const lise = await api.createBrowser('lise'); + expect(codeOf(await lise.request(LIST, { list: 'TRIED', after: 'not-a-cursor' }))).toBe('BAD_USER_INPUT'); + }); + }); + + describe('Wine.myLists', () => { + it('asks the database once for a whole page of wines', async () => { + const wines = await api.createWines(3); + const nina = await api.createBrowser('nina'); + for (const wine of wines) await nina.request(SET, set(wine, 'FAVOURITE')); + + // A real page, like the profile shows: all wines on it come from one query, so their + // myLists are asked for at the same time, and DataLoader sends them as one query. + const PAGE = `query { me { wines(list: FAVOURITE, first: 24) { edges { node { id myLists } } } } }`; + const spy = vi.spyOn(pool, 'query'); + try { + const page = pageOf(await nina.request(PAGE)); + expect(page.edges.map((edge) => edge.node)).toEqual( + [...wines].reverse().map((id) => ({ id, myLists: ['FAVOURITE'] })), + ); + // Only the loader's query: the page itself also reads user_wine, for the page and the count. + const myListsQueries = spy.mock.calls.filter(([sql]) => + String(sql).includes('SELECT wine_id, list FROM user_wine'), + ); + expect(myListsQueries).toHaveLength(1); + } finally { + spy.mockRestore(); + } + }); + }); + + describe('top favourites', () => { + /** A logged-in user with `count` new wines, all on the favourites. */ + async function userWithFavourites(name: string, count: number) { + const wines = await api.createWines(count); + const browser = await api.createBrowser(name); + for (const wine of wines) await browser.request(SET, set(wine, 'FAVOURITE')); + return { browser, wines }; + } + + it('cannot be changed without login', async () => { + const visitor = await api.createBrowser(); + expect(codeOf(await visitor.request(SET_TOP, { wineIds: [] }))).toBe('UNAUTHENTICATED'); + }); + + it('keeps the order the user chose, and can be replaced and cleared', async () => { + const { browser: eva, wines } = await userWithFavourites('eva', 5); + const [a, b, c, d, e] = wines; + + expect(topOf(await eva.request(SET_TOP, { wineIds: [c, a, d, b] }))).toEqual([c, a, d, b]); + expect(topOf(await eva.request(TOP))).toEqual([c, a, d, b]); + + expect(topOf(await eva.request(SET_TOP, { wineIds: [e, c] }))).toEqual([e, c]); + expect(topOf(await eva.request(SET_TOP, { wineIds: [] }))).toEqual([]); + }); + + it('refuses more than four, a wine twice and wines that are not favourites, and keeps the old list', async () => { + const { browser: jon, wines } = await userWithFavourites('jon', 5); + const [a, b, c, d, e] = wines; + const [tried] = await api.createWines(1); + await jon.request(SET, set(tried, 'TRIED')); + await jon.request(SET_TOP, { wineIds: [a, b] }); + + for (const wineIds of [[a, b, c, d, e], [a, a], [a, tried], ['1999999999'], ['not-an-id']]) { + expect(codeOf(await jon.request(SET_TOP, { wineIds }))).toBe('BAD_USER_INPUT'); + } + expect(topOf(await jon.request(TOP))).toEqual([a, b]); + }); + + it('loses a wine that is taken off the favourites, and keeps the order of the rest', async () => { + const { browser: mia, wines } = await userWithFavourites('mia', 3); + const [a, b, c] = wines; + await mia.request(SET_TOP, { wineIds: [a, b, c] }); + + await mia.request(SET, set(b, 'FAVOURITE', false)); + + expect(topOf(await mia.request(TOP))).toEqual([a, c]); + // The free place can be used again. + await mia.request(SET, set(b, 'FAVOURITE')); + expect(topOf(await mia.request(SET_TOP, { wineIds: [b, a, c] }))).toEqual([b, a, c]); + }); + + it('keeps the lists of each user apart', async () => { + const { browser: ida, wines } = await userWithFavourites('ida', 1); + const { browser: leo } = await userWithFavourites('leo', 0); + await ida.request(SET_TOP, { wineIds: wines }); + + // Leo cannot use Ida's favourite, and does not see her top list as his own. + expect(codeOf(await leo.request(SET_TOP, { wineIds: wines }))).toBe('BAD_USER_INPUT'); + expect(topOf(await leo.request(TOP))).toEqual([]); + expect(topOf(await ida.request(TOP))).toEqual(wines); + }); + + it('handles two changes at the same time without an error, and ends with one of them', async () => { + const { browser: ask, wines } = await userWithFavourites('ask', 4); + const [a, b, c, d] = wines; + + const results = await Promise.all([ + ask.request(SET_TOP, { wineIds: [a, b, c, d] }), + ask.request(SET_TOP, { wineIds: [d, c, b, a] }), + ]); + + expect(results.map((result) => result.errors)).toEqual([undefined, undefined]); + expect([ + [a, b, c, d], + [d, c, b, a], + ]).toContainEqual(topOf(await ask.request(TOP))); + }); + + it('is checked by the database as well: at most one wine per place, and only favourites', async () => { + const { browser: ulf, wines } = await userWithFavourites('ulf', 2); + const [a, b] = wines; + await ulf.request(SET_TOP, { wineIds: [a] }); + const userId = ( + await pool.query<{ user_id: number }>( + "SELECT user_id FROM user_wine WHERE wine_id = $1 AND list = 'FAVOURITE'", + [Number(a)], + ) + ).rows[0].user_id; + + const setTop = (list: string, wine: string, position: number) => + pool.query( + `INSERT INTO user_wine (user_id, wine_id, list, top_position) VALUES ($1, $2, $3, $4) + ON CONFLICT ON CONSTRAINT user_wine_once DO UPDATE SET top_position = EXCLUDED.top_position`, + [userId, Number(wine), list, position], + ); + + await expect(setTop('FAVOURITE', b, 1)).rejects.toMatchObject({ code: '23505', constraint: 'user_wine_top' }); + await expect(setTop('TRIED', b, 2)).rejects.toMatchObject({ + code: '23514', + constraint: 'user_wine_top_only_favourites', + }); + }); + }); + + describe('a saved review', () => { + const review = (wineId: string, rating = 4) => ({ input: { wineId, rating, comment: 'Smakte godt' } }); + + it('puts the wine on «Har prøvd» and takes it off «Vil prøve»', async () => { + const [wine] = await api.createWines(1); + const rut = await api.createBrowser('rut'); + await rut.request(SET, set(wine, 'WANT_TO_TRY')); + await rut.request(SET, set(wine, 'FAVOURITE')); + + const result = await rut.request(SAVE_REVIEW, review(wine)); + + expect(result.errors).toBeUndefined(); + const saved = result.data?.saveReview as { wine: { myLists: string[] } }; + expect(saved.wine.myLists).toEqual(['FAVOURITE', 'TRIED']); + expect(pageOf(await rut.request(LIST, { list: 'WANT_TO_TRY' })).totalCount).toBe(0); + }); + + it('keeps the wine once on «Har prøvd» when the review is edited, and there when it is deleted', async () => { + const [wine] = await api.createWines(1); + const bo = await api.createBrowser('bo'); + await bo.request(SAVE_REVIEW, review(wine, 3)); + await bo.request(SAVE_REVIEW, review(wine, 4.5)); + expect(pageOf(await bo.request(LIST, { list: 'TRIED' })).totalCount).toBe(1); + + expect((await bo.request(DELETE_REVIEW, { wineId: wine })).data).toEqual({ deleteReview: true }); + expect(listsOf(await bo.request(MY_LISTS, { id: wine })).myLists).toEqual(['TRIED']); + }); + + it('changes no list when the review is refused', async () => { + const [wine] = await api.createWines(1); + const vera = await api.createBrowser('vera'); + await vera.request(SET, set(wine, 'WANT_TO_TRY')); + + expect(codeOf(await vera.request(SAVE_REVIEW, review(wine, 7)))).toBe('BAD_USER_INPUT'); + expect(codeOf(await vera.request(SAVE_REVIEW, review('1999999999')))).toBe('BAD_USER_INPUT'); + + expect(listsOf(await vera.request(MY_LISTS, { id: wine })).myLists).toEqual(['WANT_TO_TRY']); + expect(pageOf(await vera.request(LIST, { list: 'TRIED' })).totalCount).toBe(0); + }); + }); +}); diff --git a/backend/src/lists/resolvers.ts b/backend/src/lists/resolvers.ts new file mode 100644 index 0000000..e70e097 --- /dev/null +++ b/backend/src/lists/resolvers.ts @@ -0,0 +1,101 @@ +// Resolvers for the wine lists. The user is always the one in the session, never an argument. +import { GraphQLError } from 'graphql'; +import { AuthErrorCode, authError } from '../auth/errors'; +import { toGraphQLUser } from '../auth/resolvers'; +import { encodeIdCursor, toConnection } from '../connection'; +import type { Context } from '../context'; +import { isForeignKeyViolation } from '../db-errors'; +import { withTransaction } from '../db'; +import { toWine } from '../resolvers'; +import { validateWineId } from '../review-input'; +import { + findListPage, + findTopFavourites, + setTopFavourites, + setWineInList, + TopFavouritesError, + type WineList, +} from './wine-lists'; + +/** The most wines one page of a list can have. */ +const MAX_PAGE_SIZE = 50; + +const badInput = (message: string) => new GraphQLError(message, { extensions: { code: 'BAD_USER_INPUT' } }); +const wineNotFound = () => badInput('Wine not found.'); + +export const listResolvers = { + Mutation: { + async setWineInList( + _parent: unknown, + args: { wineId: string; list: WineList; inList: boolean }, + { auth, loaders }: Context, + ) { + const user = await auth.requireUser(); + const wineId = validateWineId(args.wineId); + try { + await withTransaction((client) => + setWineInList(client, { userId: user.id, wineId, list: args.list, inList: args.inList }), + ); + } catch (error) { + if (isForeignKeyViolation(error, 'user_wine_wine_id_fkey')) throw wineNotFound(); + // The account was deleted after the session was checked, in the same moment. + if (isForeignKeyViolation(error, 'user_wine_user_id_fkey')) { + throw authError(AuthErrorCode.UNAUTHENTICATED, 'You must be logged in.'); + } + throw error; + } + + // The answer must show the lists after the change. + loaders.myLists(user.id).clear(wineId); + const row = await loaders.wines.load(wineId); + if (!row) throw wineNotFound(); + return toWine(row); + }, + + async setTopFavourites(_parent: unknown, args: { wineIds: string[] }, { auth }: Context) { + const user = await auth.requireUser(); + const wineIds = args.wineIds.map(validateWineId); + try { + await withTransaction((client) => setTopFavourites(client, { userId: user.id, wineIds })); + } catch (error) { + if (error instanceof TopFavouritesError) throw badInput(error.message); + throw error; + } + return toGraphQLUser(user); + }, + }, + + // Lists are public, so this works for any user, also on other users' profiles later. + User: { + async wines( + user: { id: string }, + args: { list: WineList; first?: number | null; after?: string | null }, + ) { + const first = Math.min(Math.max(args.first ?? 24, 1), MAX_PAGE_SIZE); + const { rows, totalCount } = await findListPage({ + userId: Number(user.id), + list: args.list, + first, + after: args.after, + }); + return toConnection({ + rows, + first, + totalCount, + toNode: toWine, + cursorFor: (row) => encodeIdCursor(row.entry_id), + }); + }, + + async topFavourites(user: { id: string }) { + return (await findTopFavourites(Number(user.id))).map(toWine); + }, + }, + + Wine: { + async myLists(wine: { id: string }, _args: unknown, { auth, loaders }: Context) { + const user = await auth.currentUser(); + return user ? loaders.myLists(user.id).load(Number(wine.id)) : []; + }, + }, +}; diff --git a/backend/src/lists/schema.ts b/backend/src/lists/schema.ts new file mode 100644 index 0000000..97c28fa --- /dev/null +++ b/backend/src/lists/schema.ts @@ -0,0 +1,41 @@ +// GraphQL types for the wine lists. Extends User, Wine and Mutation. +export const listTypeDefs = `#graphql + "The lists a user can put a wine on. All lists are public on the profile." + enum WineList { + FAVOURITE + "«Vil prøve»" + WANT_TO_TRY + "«Har prøvd»" + TRIED + } + + extend type User { + "The wines on one of the user's lists, newest first. Use pageInfo.endCursor as 'after' to load more." + wines(list: WineList!, first: Int = 24, after: String): WineConnection! + + "Up to four of the user's favourites, in the order the user chose." + topFavourites: [Wine!]! + } + + extend type Wine { + "The lists the logged-in user has put this wine on. Empty when logged out." + myLists: [WineList!]! + } + + extend type Mutation { + """ + Puts the wine on the list (inList: true) or takes it off (false). Doing it twice changes + nothing. Putting it on TRIED takes it off WANT_TO_TRY. Returns the wine, so myLists can be + updated in the cache. Requires login (UNAUTHENTICATED). An unknown wine gives BAD_USER_INPUT. + """ + setWineInList(wineId: ID!, list: WineList!, inList: Boolean!): Wine! + + """ + Replaces the top list among the favourites with these wines, in this order. An empty list + clears it. At most four wines, each once, and all on the user's favourites; otherwise + BAD_USER_INPUT, and the old top list is kept. Returns the user, so topFavourites can be + updated in the cache. Requires login (UNAUTHENTICATED). + """ + setTopFavourites(wineIds: [ID!]!): User! + } +`; diff --git a/backend/src/lists/wine-lists.ts b/backend/src/lists/wine-lists.ts new file mode 100644 index 0000000..c86d243 --- /dev/null +++ b/backend/src/lists/wine-lists.ts @@ -0,0 +1,134 @@ +// The wine lists and their rules, and the SQL that changes and reads them. +// The database checks what it can (see the user_wine migration); the rules that span two +// lists are here, and run in one transaction. +import type { PoolClient } from 'pg'; +import { decodeIdCursor } from '../connection'; +import { pool } from '../db'; +import type { WineRow } from '../loaders'; + +/** The same values as the GraphQL enum WineList and the CHECK on user_wine.list. */ +export const WINE_LISTS = ['FAVOURITE', 'WANT_TO_TRY', 'TRIED'] as const; +export type WineList = (typeof WINE_LISTS)[number]; + +/** The lists in a fixed order, so the API always answers the same way. */ +export function sortLists(lists: WineList[]): WineList[] { + return WINE_LISTS.filter((list) => lists.includes(list)); +} + +/** + * Puts the wine on the list, or takes it off. Doing it twice changes nothing. + * Rule: a wine on «Har prøvd» is taken off «Vil prøve». + */ +export async function setWineInList( + client: PoolClient, + { userId, wineId, list, inList }: { userId: number; wineId: number; list: WineList; inList: boolean }, +): Promise { + if (!inList) { + await client.query('DELETE FROM user_wine WHERE user_id = $1 AND wine_id = $2 AND list = $3', [ + userId, + wineId, + list, + ]); + return; + } + + await client.query( + `INSERT INTO user_wine (user_id, wine_id, list) VALUES ($1, $2, $3) + ON CONFLICT ON CONSTRAINT user_wine_once DO NOTHING`, + [userId, wineId, list], + ); + if (list === 'TRIED') { + await client.query( + "DELETE FROM user_wine WHERE user_id = $1 AND wine_id = $2 AND list = 'WANT_TO_TRY'", + [userId, wineId], + ); + } +} + +/** How many wines the top list among the favourites can hold. Same limit as the CHECK on top_position. */ +export const MAX_TOP_FAVOURITES = 4; + +/** Why setTopFavourites refused the new order. The resolver turns it into BAD_USER_INPUT. */ +export class TopFavouritesError extends Error {} + +/** + * Replaces the user's top list with `wineIds`, in that order (position 1 first). An empty list + * clears it. Rules: at most four wines, no wine twice, and all of them on the user's favourites. + * Taking a wine off the favourites deletes its row, and with it its place in the top list. + */ +export async function setTopFavourites( + client: PoolClient, + { userId, wineIds }: { userId: number; wineIds: number[] }, +): Promise { + if (wineIds.length > MAX_TOP_FAVOURITES) { + throw new TopFavouritesError(`The top list can hold at most ${MAX_TOP_FAVOURITES} wines.`); + } + if (new Set(wineIds).size !== wineIds.length) { + throw new TopFavouritesError('A wine can only be in the top list once.'); + } + + // One change of the top list at a time per user. Without the lock, two changes at the same + // time could both pass the first UPDATE and then collide on the index user_wine_top. + // NO KEY UPDATE does not block the foreign key checks when the user adds wines or reviews. + await client.query('SELECT 1 FROM app_user WHERE id = $1 FOR NO KEY UPDATE', [userId]); + + // Clear first, so the new positions never collide with the old ones on the unique index. + await client.query( + 'UPDATE user_wine SET top_position = NULL WHERE user_id = $1 AND top_position IS NOT NULL', + [userId], + ); + const placed = await client.query( + `UPDATE user_wine SET top_position = top.position + FROM unnest($2::integer[]) WITH ORDINALITY AS top(wine_id, position) + WHERE user_wine.user_id = $1 AND user_wine.list = 'FAVOURITE' AND user_wine.wine_id = top.wine_id`, + [userId, wineIds], + ); + // A wine that is not a favourite (or does not exist) matched no row. Throwing rolls back the + // transaction, so the old top list is kept. + if (placed.rowCount !== wineIds.length) { + throw new TopFavouritesError('Only favourites can be in the top list.'); + } +} + +/** The user's top list, position 1 first. Positions can have gaps after a favourite is removed. */ +export async function findTopFavourites(userId: number) { + const { rows } = await pool.query( + `SELECT wine.* + FROM user_wine + JOIN wine ON wine.id = user_wine.wine_id + WHERE user_wine.user_id = $1 AND user_wine.top_position IS NOT NULL + ORDER BY user_wine.top_position`, + [userId], + ); + return rows; +} + +/** A row of the wine table, plus the id of its row in the list (for the cursor). */ +export interface ListedWineRow extends WineRow { + entry_id: number; +} + +/** One page of a list, newest first, and how many wines the list has in all. */ +export async function findListPage( + { userId, list, first, after }: { userId: number; list: WineList; first: number; after?: string | null }, +) { + const before = decodeIdCursor(after); + // The index user_wine_list_newest covers both queries. + const [page, count] = await Promise.all([ + pool.query( + `SELECT wine.*, user_wine.id AS entry_id + FROM user_wine + JOIN wine ON wine.id = user_wine.wine_id + WHERE user_wine.user_id = $1 AND user_wine.list = $2 + AND ($3::integer IS NULL OR user_wine.id < $3) + ORDER BY user_wine.id DESC + LIMIT $4`, + [userId, list, before, first + 1], + ), + pool.query<{ total: number }>( + 'SELECT count(*)::int AS total FROM user_wine WHERE user_id = $1 AND list = $2', + [userId, list], + ), + ]); + return { rows: page.rows, totalCount: count.rows[0].total }; +} diff --git a/backend/src/loaders.ts b/backend/src/loaders.ts index 6fe52fb..e4530dc 100644 --- a/backend/src/loaders.ts +++ b/backend/src/loaders.ts @@ -2,6 +2,7 @@ // 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'; +import { sortLists, type WineList } from './lists/wine-lists'; // A row from the wine table, as returned by pg. export interface WineRow { @@ -125,7 +126,28 @@ export function createLoaders() { return userIds.map((id) => byId.get(id) ?? null); }); - return { wines, studentRatings, ratingDistributions, reviews, usernames }; + // One loader per user, because the user is part of the query. In practice there is only one: + // the logged-in user. A page of wines then asks for their lists in one query. + const listLoaders = new Map>(); + + function myLists(userId: number) { + let loader = listLoaders.get(userId); + if (!loader) { + loader = new DataLoader(async (wineIds) => { + const result = await pool.query<{ wine_id: number; list: WineList }>( + 'SELECT wine_id, list FROM user_wine WHERE user_id = $1 AND wine_id = ANY($2)', + [userId, [...wineIds]], + ); + return wineIds.map((id) => + sortLists(result.rows.filter((row) => row.wine_id === id).map((row) => row.list)), + ); + }); + listLoaders.set(userId, loader); + } + return loader; + } + + return { wines, studentRatings, ratingDistributions, reviews, usernames, myLists }; } export type Loaders = ReturnType; \ No newline at end of file diff --git a/backend/src/resolvers.ts b/backend/src/resolvers.ts index 34f7775..df139e6 100644 --- a/backend/src/resolvers.ts +++ b/backend/src/resolvers.ts @@ -1,13 +1,16 @@ // Resolvers: the functions that fetch data for each field in the schema. import { GraphQLError } from 'graphql'; -import { pool } from './db'; +import { AuthErrorCode, authError } from './auth/errors'; +import { decodeIdCursor, encodeIdCursor, toConnection } from './connection'; +import { isForeignKeyViolation } from './db-errors'; +import { pool, withTransaction } from './db'; import type { Context } from './context'; +import { setWineInList } from './lists/wine-lists'; import { type ReviewRow, type WineRow } from './loaders'; import { validateReviewInput, validateWineId, type ReviewInput } from './review-input'; import { buildFilterOptionsQueries, buildWinesQuery, - decodeCursor, encodeCursor, type FilterArgs, type WinesArgs, @@ -17,8 +20,8 @@ import { UPDATE_WINE_RATING_STATS } from './rating-stats'; // The most reviews one query can ask for. const MAX_REVIEWS = 50; -// Converts database names (snake_case) to GraphQL names (camelCase). -function toWine(row: WineRow) { +// Converts database names (snake_case) to GraphQL names (camelCase). Also used by the lists. +export function toWine(row: WineRow) { return { id: String(row.id), name: row.name, @@ -53,26 +56,6 @@ function toReview(row: ReviewRow) { }; } -/** - * A page in the GraphQL connection format. `rows` holds one row more than `first` - * when there is a next page; that row is only used to set hasNextPage. - */ -function toConnection( - rows: Row[], - { first, offset, totalCount }: { first: number; offset: number; totalCount: number }, - toNode: (row: Row) => Node, -) { - const edges = rows.slice(0, first).map((row, i) => ({ - cursor: encodeCursor(offset + i + 1), - node: toNode(row), - })); - return { - totalCount, - edges, - pageInfo: { hasNextPage: rows.length > first, endCursor: edges.at(-1)?.cursor ?? null }, - }; -} - /** 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); @@ -95,11 +78,13 @@ export const resolvers = { pool.query<{ total: number }>(query.countSql, query.countParams), ]); - return toConnection( - list.rows, - { first: query.first, offset: query.offset, totalCount: count.rows[0].total }, - toWine, - ); + return toConnection({ + rows: list.rows, + first: query.first, + totalCount: count.rows[0].total, + toNode: toWine, + cursorFor: (_row, index) => encodeCursor(query.offset + index + 1), + }); }, async wine(_parent: unknown, args: { id: string }) { @@ -138,31 +123,50 @@ export const resolvers = { // The author is always the logged-in user from the session, never an argument. Mutation: { - async saveReview(_parent: unknown, args: { input: ReviewInput }, { auth }: Context) { + async saveReview(_parent: unknown, args: { input: ReviewInput }, { auth, loaders }: Context) { const user = await auth.requireUser(); const review = validateReviewInput(args.input); try { - // Adds the review, or updates the user's earlier review of the same 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, user.id, review.rating, review.comment], - ); - // The new review counts in the wine's average right away. - await pool.query(UPDATE_WINE_RATING_STATS, [review.wineId]); - return toReview(result.rows[0]); + // All or nothing: the review, the wine on «Har prøvd», and the wine's average. + const row = await withTransaction(async (client) => { + // Adds the review, or updates the user's earlier review of the same wine. + const result = await client.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, user.id, review.rating, review.comment], + ); + // Rule: a reviewed wine has been tried. This also takes it off «Vil prøve». + await setWineInList(client, { + userId: user.id, + wineId: review.wineId, + list: 'TRIED', + inList: true, + }); + // The new review counts in the wine's average right away. + await client.query(UPDATE_WINE_RATING_STATS, [review.wineId]); + return result.rows[0]; + }); + loaders.myLists(user.id).clear(review.wineId); + return toReview(row); } catch (error) { - // 23503 = foreign key violation: the wine does not exist. - if ((error as { code?: string }).code === '23503') { + if (isForeignKeyViolation(error, 'review_wine_id_fkey')) { throw new GraphQLError('Wine not found.', { extensions: { code: 'BAD_USER_INPUT' } }); } + // The account was deleted after the session was checked, in the same moment. + if ( + isForeignKeyViolation(error, 'review_user_id_fkey') || + isForeignKeyViolation(error, 'user_wine_user_id_fkey') + ) { + throw authError(AuthErrorCode.UNAUTHENTICATED, 'You must be logged in.'); + } throw error; } }, + // The wine stays on «Har prøvd»: the user has still tried it. async deleteReview(_parent: unknown, args: { wineId: string }, { auth }: Context) { const user = await auth.requireUser(); const wineId = validateWineId(args.wineId); @@ -202,24 +206,32 @@ export const resolvers = { // User comes from auth/resolvers.ts. Fields that belong to other features are added here. User: { + // Newest written first. The order is by id, which an edit does not change, so editing a + // review while someone pages through the list neither skips nor repeats one. async reviews(user: { id: string }, args: { first?: number | null; after?: string | null }) { const userId = Number(user.id); const first = limitReviews(args.first, 10); - const offset = decodeCursor(args.after); - // The index review_user_updated covers both queries. + const before = decodeIdCursor(args.after); + // The index review_user_id covers both queries. const [list, count] = await Promise.all([ pool.query( `SELECT * FROM review - WHERE user_id = $1 - ORDER BY updated_at DESC, id DESC - LIMIT $2 OFFSET $3`, - [userId, first + 1, offset], + WHERE user_id = $1 AND ($2::integer IS NULL OR id < $2) + ORDER BY id DESC + LIMIT $3`, + [userId, before, first + 1], ), pool.query<{ total: number }>('SELECT count(*)::int AS total FROM review WHERE user_id = $1', [ userId, ]), ]); - return toConnection(list.rows, { first, offset, totalCount: count.rows[0].total }, toReview); + return toConnection({ + rows: list.rows, + first, + totalCount: count.rows[0].total, + toNode: toReview, + cursorFor: (row) => encodeIdCursor(row.id), + }); }, }, diff --git a/backend/src/review-api.db.test.ts b/backend/src/review-api.db.test.ts index c5e3b8e..09be536 100644 --- a/backend/src/review-api.db.test.ts +++ b/backend/src/review-api.db.test.ts @@ -199,6 +199,22 @@ describe.skipIf(!url)('reviews API (PostgreSQL)', () => { expect(second.pageInfo.hasNextPage).toBe(false); }); + it('neither skips nor repeats a review that is edited while paging', async () => { + const siv = await createBrowser('siv'); + await siv.request(SAVE, save(4)); + await siv.request(SAVE, { input: { wineId: otherWineId, rating: 2 } }); + + const first = pageOf(await siv.request(MY_REVIEWS, { first: 1 })); + expect(first.edges.map((edge) => edge.node.wine.id)).toEqual([otherWineId]); + + // The older review is edited before the next page. Sorted by updated_at, it would jump + // to the top and never show up on the next page. + await siv.request(SAVE, save(5)); + + const second = pageOf(await siv.request(MY_REVIEWS, { first: 1, after: first.pageInfo.endCursor })); + expect(second.edges.map((edge) => edge.node)).toEqual([{ rating: 5, wine: { id: wineId } }]); + }); + it('rejects a cursor that was not made by the API', async () => { const ina = await createBrowser('ina'); expect(codeOf(await ina.request(MY_REVIEWS, { after: 'not-a-cursor' }))).toBe('BAD_USER_INPUT'); diff --git a/backend/src/schema.ts b/backend/src/schema.ts index 7d12127..cedace9 100644 --- a/backend/src/schema.ts +++ b/backend/src/schema.ts @@ -152,10 +152,16 @@ export const typeDefs = `#graphql } type Mutation { - "Adds a review, or updates the user's earlier review of the same wine. Requires login (UNAUTHENTICATED)." + """ + Adds a review, or updates the user's earlier review of the same wine. Also puts the wine on + the user's TRIED list (and so takes it off WANT_TO_TRY). Requires login (UNAUTHENTICATED). + """ saveReview(input: ReviewInput!): Review! - "Deletes the user's review of a wine. Returns false if there was none. Requires login (UNAUTHENTICATED)." + """ + Deletes the user's review of a wine. Returns false if there was none. The wine stays on the + TRIED list. Requires login (UNAUTHENTICATED). + """ deleteReview(wineId: ID!): Boolean! } `; \ No newline at end of file diff --git a/backend/src/scripts/seed-demo-user.ts b/backend/src/scripts/seed-demo-user.ts new file mode 100644 index 0000000..2161ad1 --- /dev/null +++ b/backend/src/scripts/seed-demo-user.ts @@ -0,0 +1,28 @@ +// Creates the demo user, or resets it. Usage: npm run db:seed:demo (after db:migrate and a wine import). +// The username and password are in demo-user.ts and in the README. +import { pool, withTransaction } from '../db'; +import { DEMO_PASSWORD, DEMO_USERNAME, DEMO_WINE_COUNT, seedDemoUser } from '../demo/demo-user'; + +async function main() { + // Well-known wines make a better demo: the ones with the most ratings. Ties by id, so the + // choice is the same each time on the same data. + const { rows } = await pool.query<{ id: number }>( + 'SELECT id FROM wine WHERE community_count > 0 ORDER BY community_count DESC, id LIMIT $1', + [DEMO_WINE_COUNT], + ); + if (rows.length < DEMO_WINE_COUNT) { + throw new Error( + `Found ${rows.length} rated wines, need ${DEMO_WINE_COUNT}. Import wines first (docs/setup.md).`, + ); + } + + await withTransaction((client) => seedDemoUser(client, { wineIds: rows.map((row) => row.id) })); + console.log(`Demo user ready. Username: ${DEMO_USERNAME} Password: ${DEMO_PASSWORD}`); +} + +main() + .catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; + }) + .finally(() => pool.end()); diff --git a/backend/src/server.ts b/backend/src/server.ts index deb63ef..47b423e 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -2,23 +2,17 @@ import { ApolloServer } from '@apollo/server'; import { expressMiddleware } from '@as-integrations/express5'; import express from 'express'; import { createAuthService } from './auth/auth-service'; -import { authResolvers } from './auth/resolvers'; -import { authTypeDefs } from './auth/schema'; import { createPgUserStore } from './auth/user-store'; import { createContextFactory, type Context } from './context'; import { pool } from './db'; -import { resolvers } from './resolvers'; -import { typeDefs } from './schema'; +import { allResolvers, allTypeDefs } from './graphql'; const PORT = Number(process.env.PORT ?? 3001); async function main() { const app = express(); - // Each feature adds its own types and resolvers. Apollo merges the lists. - const apollo = new ApolloServer({ - typeDefs: [typeDefs, authTypeDefs], - resolvers: [resolvers, authResolvers], - }); + // Each feature adds its own types and resolvers. See graphql.ts. + const apollo = new ApolloServer({ typeDefs: allTypeDefs, resolvers: allResolvers }); const createContext = createContextFactory(createAuthService(createPgUserStore(pool))); await apollo.start(); diff --git a/backend/src/test/graphql-test-api.ts b/backend/src/test/graphql-test-api.ts new file mode 100644 index 0000000..b89164b --- /dev/null +++ b/backend/src/test/graphql-test-api.ts @@ -0,0 +1,81 @@ +// The real GraphQL API (graphql.ts) against the test database, for the *.db.test.ts files. +// Each test gets browsers that keep the session cookie, and wines of its own, far above the +// X-Wines ids, which are removed afterwards with everything that refers to them. +import { ApolloServer } from '@apollo/server'; +import { createAuthContext } from '../auth/auth-context'; +import { createAuthService } from '../auth/auth-service'; +import type { CookieJar } from '../auth/cookies'; +import { createPgUserStore } from '../auth/user-store'; +import type { Context } from '../context'; +import { pool } from '../db'; +import { allResolvers, allTypeDefs } from '../graphql'; +import { createLoaders } from '../loaders'; + +/** Cheap hashing parameters, so registering test users is fast. */ +const FAST_SCRYPT = { N: 1024, r: 8, p: 1 }; + +export interface GraphQLResult { + data?: Record | null; + errors?: readonly { message: string; extensions?: Record }[]; +} + +/** The error code of the first error, for example 'UNAUTHENTICATED'. */ +export const codeOf = (result: GraphQLResult) => result.errors?.[0]?.extensions?.code; + +/** `firstId` keeps the wines of different test files apart when they run at the same time. */ +export function createTestApi({ firstId }: { firstId: number }) { + const service = createAuthService(createPgUserStore(pool), { scryptParams: FAST_SCRYPT }); + const server = new ApolloServer({ typeDefs: allTypeDefs, resolvers: allResolvers }); + const userIds: number[] = []; + const wineIds: number[] = []; + let nextWineId = firstId + Math.floor(Math.random() * 1_000_000); + + /** Wines of the test's own. Returns their ids as the API writes them. */ + async function createWines(count: number): Promise { + const ids = Array.from({ length: count }, () => nextWineId++); + await pool.query( + `INSERT INTO wine (id, name, type, search_text) + SELECT id, 'Testvin ' || id, 'Red', 'testvin ' || id FROM unnest($1::integer[]) AS id`, + [ids], + ); + wineIds.push(...ids); + return ids.map(String); + } + + /** A browser that keeps the session cookie. With `as`, a new user is registered and logged in. */ + async function createBrowser(as?: string) { + let cookie: string | undefined; + let username: string | undefined; + const jar: CookieJar = { + setSession: (token) => (cookie = token), + clearSession: () => (cookie = undefined), + }; + + if (as) { + username = `t_${as}_${Math.random().toString(36).slice(2, 10)}`.slice(0, 30); + const { user, session } = await service.register({ username, password: 'langt-nok-passord' }); + userIds.push(user.id); + cookie = session.token; + } + + async function request(query: string, variables?: Record): Promise { + const response = await server.executeOperation( + { query, variables }, + { contextValue: { loaders: createLoaders(), auth: createAuthContext(service, cookie, jar) } }, + ); + if (response.body.kind !== 'single') throw new Error('Expected a single result'); + return response.body.singleResult; + } + + return { request, username }; + } + + /** Removes what the tests made, and closes the pool. Call it in afterAll. */ + async function close() { + await pool.query('DELETE FROM wine WHERE id = ANY($1)', [wineIds]); + await pool.query('DELETE FROM app_user WHERE id = ANY($1)', [userIds]); + await pool.end(); + } + + return { createBrowser, createWines, close }; +} diff --git a/backend/src/wine-query.test.ts b/backend/src/wine-query.test.ts index 7befe7d..0c31803 100644 --- a/backend/src/wine-query.test.ts +++ b/backend/src/wine-query.test.ts @@ -122,4 +122,10 @@ describe('cursor', () => { it('rejects an invalid cursor', () => { expect(() => decodeCursor('not-a-cursor')).toThrow('Invalid cursor.'); }); + + it('rejects an offset too large for the database, instead of a server error', () => { + const huge = Buffer.from(`offset:${'9'.repeat(25)}`).toString('base64'); + expect(() => decodeCursor(huge)).toThrow('Invalid cursor.'); + expect(() => decodeCursor(Buffer.from('offset:1000000001').toString('base64'))).toThrow('Invalid cursor.'); + }); }); \ No newline at end of file diff --git a/backend/src/wine-query.ts b/backend/src/wine-query.ts index 08df7fb..daac614 100644 --- a/backend/src/wine-query.ts +++ b/backend/src/wine-query.ts @@ -45,13 +45,17 @@ export function encodeCursor(offset: number): string { return Buffer.from(`offset:${offset}`).toString('base64'); } +/** No catalogue is this large. Larger offsets would only make the database fail. */ +const MAX_OFFSET = 1_000_000_000; + export function decodeCursor(cursor: string | null | undefined): number { if (!cursor) return 0; - const match = /^offset:(\d+)$/.exec(Buffer.from(cursor, 'base64').toString('utf8')); - if (!match) { - throw new GraphQLError('Invalid cursor.', { extensions: { code: 'BAD_USER_INPUT' } }); + const match = /^offset:(\d{1,10})$/.exec(Buffer.from(cursor, 'base64').toString('utf8')); + const offset = match ? Number(match[1]) : NaN; + if (!Number.isInteger(offset) || offset > MAX_OFFSET) { + throw new GraphQLError('Invalid cursor.', { extensions: { code: 'BAD_USER_INPUT' } }); } - return Number(match[1]); + return offset; } /** Escapes % and _ so the user's text is matched literally by ILIKE. */ diff --git a/backend/vitest.config.ts b/backend/vitest.config.mts similarity index 100% rename from backend/vitest.config.ts rename to backend/vitest.config.mts diff --git a/docs/api.md b/docs/api.md index 779a18e..7e8e404 100644 --- a/docs/api.md +++ b/docs/api.md @@ -15,6 +15,7 @@ From `backend/`: ```bash npm run db:migrate # create tables and indexes (safe to run again) npm run db:seed:test # load the Test version (safe to run again) +npm run db:seed:demo # the demo user, see "Demo user" below (safe to run again) ``` Citation: de Azambuja, R.X.; Morais, A.J.; Filipe, V. X-Wines: A Wine Dataset for @@ -183,12 +184,14 @@ Usernames are trimmed and lowercased. Passwords need 8 to 128 characters and are In the resolver, call `requireUser()` on the context and use the returned id: ```ts -async addFavourite(_parent: unknown, args: { wineId: string }, { auth }: Context) { +async setWineInList(_parent: unknown, args: { wineId: string; list: WineList; inList: boolean }, { auth }: Context) { const user = await auth.requireUser(); // throws UNAUTHENTICATED - // INSERT INTO favourite (user_id, wine_id) VALUES ($1, $2) with user.id + // ... INSERT INTO user_wine (user_id, wine_id, list) with user.id } ``` +`backend/src/lists/resolvers.ts` is a complete example. + Never take a user id from the arguments: the user is always the one in the session. In the frontend, put the page under `` in `App.tsx`, and read the user with `useAuthenticatedUser()`. @@ -201,12 +204,92 @@ In the frontend, put the page under `` in `App.tsx`, and read the u | `auth/auth-service.test.ts` | Register, login, logout and session expiry with an in-memory store | | `auth/auth-api.test.ts` | Real GraphQL requests through Apollo Server, with a fake browser that keeps the cookie: two browsers, logout, forged cookies, error codes, and that no field exposes the password hash | | `auth/user-store.db.test.ts` | The SQL against PostgreSQL. Skipped unless `TEST_DATABASE_URL` is set | -| `review-api.db.test.ts` | Reviews through Apollo Server against PostgreSQL, with one fake browser per user: login required, one review per user and wine, users cannot see or delete each other's reviews, the average follows at once, old anonymous reviews, and `User.reviews` with pages. Skipped unless `TEST_DATABASE_URL` is set | +| `review-api.db.test.ts` | Reviews through Apollo Server against PostgreSQL, with one fake browser per user: login required, one review per user and wine, users cannot see or delete each other's reviews, the average follows at once, old anonymous reviews, and `User.reviews` with pages that neither skip nor repeat a review edited meanwhile. Skipped unless `TEST_DATABASE_URL` is set | + +## Wine lists + +Each user has three lists of wines, and a top 4 among the favourites. All of them are public, so +they can be shown on any profile. The code is in `backend/src/lists/`, the table in the migration +`*_create-user-wine.sql`. + +| List | In the interface | Enum value | +|---|---|---| +| Favourites | Heart | `FAVOURITE` | +| «Vil prøve» | Bookmark | `WANT_TO_TRY` | +| «Har prøvd» | Button «Har prøvd» | `TRIED` | + +The table `user_wine` has one row per user, list and wine: `id`, `user_id`, `wine_id`, `list`, +`added_at` and `top_position` (1 to 4, only on favourites). + +### Rules + +| Rule | Where it is enforced | +|---|---| +| A wine is at most once on each list | `UNIQUE (user_id, list, wine_id)`. Adding it again changes nothing | +| A wine can be on several lists, such as a favourite that is also tried | No rule against it | +| «Har prøvd» takes the wine off «Vil prøve» | `setWineInList` in `wine-lists.ts`, in the same transaction | +| A saved review puts the wine on «Har prøvd» | `saveReview`, in the same transaction as the review. Deleting the review keeps the wine on «Har prøvd» | +| The top 4 has at most four wines, each once, all favourites | `setTopFavourites` checks and gives a clear error. The database checks it too: `top_position BETWEEN 1 AND 4`, a unique index on `(user_id, top_position)`, and `CHECK (top_position IS NULL OR list = 'FAVOURITE')` | +| A wine taken off the favourites leaves the top 4 | The row is deleted, and its place with it. The others keep their order | +| Deleting a user or a wine deletes its rows | `ON DELETE CASCADE` | + +### Schema + +```graphql +enum WineList { FAVOURITE WANT_TO_TRY TRIED } + +extend type User { + wines(list: WineList!, first: Int = 24, after: String): WineConnection! # newest first, first <= 50 + topFavourites: [Wine!]! # in the chosen order +} +extend type Wine { myLists: [WineList!]! } # [] when logged out + +mutation { setWineInList(wineId: "123", list: TRIED, inList: true) { id myLists } } +mutation { setTopFavourites(wineIds: ["123", "456"]) { id topFavourites { id name } } } +``` + +`setWineInList` returns the wine and `setTopFavourites` returns the user, so Apollo Client updates +`myLists` and `topFavourites` in its cache without a new query. `setTopFavourites` replaces the whole +top 4 at once: send the wines in the new order, or `[]` to clear it. + +| Error code | When | +|---|---| +| `UNAUTHENTICATED` | Either mutation without a logged-in user | +| `BAD_USER_INPUT` | An invalid or unknown wine id, an unknown list, an invalid cursor, or a top 4 that breaks the rules above. A refused top 4 keeps the old one | + +Choices and why: + +| Choice | Why | Alternatives considered | +|---|---|---| +| One table with a `list` column | One set of queries, indexes and tests for all three lists, and a new list is one enum value | One table per list | +| `top_position` on the favourite row | A wine leaves the top 4 when it stops being a favourite, without extra code | A separate table for the top 4 | +| `setTopFavourites` takes the whole order | One call for a drag-and-drop or keyboard reorder, and the order is always valid after it | Moving one wine at a time | +| Pages by the row id (keyset), newest first | A wine added or removed meanwhile neither skips nor repeats a wine on the next page | Offset, as for the wine search | +| `Wine.myLists` with a DataLoader per user | A page of 24 wines asks for the lists in one query | One query per wine | +| Changes to the top 4 lock the user's row (`FOR NO KEY UPDATE`) | Two changes at the same time are done one after the other instead of colliding on the unique index | Retrying on a unique violation | + +### Tests + +| File | Tests | +|---|---| +| `lists/lists-api.db.test.ts` | Through Apollo Server against PostgreSQL: login required, adding and removing twice, several lists, «Har prøvd» takes the wine off «Vil prøve», users kept apart, unknown wines and lists, pages that do not skip, one query for `myLists` on a page of 24, the top 4 rules and order, two changes at once, the database constraints, and that a saved review marks the wine as tried | +| `demo/demo-user.db.test.ts` | The demo user: the documented password works, the data follows the rules, the averages are updated, and running it again gives the same state | + +## Demo user + +`npm run db:seed:demo` in `backend/` creates the user **`demo`** with the password **`kork-og-krone`**, +so the profile features can be tried without registering and filling in lists first. It has six +favourites with a top 4, five wines on «Vil prøve», seven on «Har prøvd» and five reviews, all on the +14 wines with the most ratings. + +Running it again resets the user to the same state, also the password. The password is public, so the +account must never hold anything private. Run it after `db:migrate` and a wine import, also on the VM. +The code is in `backend/src/demo/demo-user.ts`. ## Database tests The tests in `*.db.test.ts` run against a separate test database, so they never touch real data. -They only remove the rows they create. `backend/vitest.config.ts` points `DATABASE_URL` at +They only remove the rows they create. `backend/vitest.config.mts` points `DATABASE_URL` at `TEST_DATABASE_URL` while the tests run, so the database in `backend/.env` is never used by a test. Create the test database once: diff --git a/docs/manual-testing.md b/docs/manual-testing.md index e8a7129..f50b7af 100644 --- a/docs/manual-testing.md +++ b/docs/manual-testing.md @@ -90,7 +90,39 @@ Things that should fail: | `UPDATE user_session SET expires_at = now() - interval '1 minute';` and reload | Treated as logged out | | `DELETE FROM app_user WHERE username = 'test_ola';` | The user's sessions and reviews go too (`ON DELETE CASCADE`) | -## 5. Accessibility +## 5. Wine lists and the top 4 + +The interface for the lists comes later, so test them through the API. Log in with curl as in section 4, +then define a short helper and pick a wine: + +```bash +q() { curl -s -b /tmp/kk.jar $API -H "$H" -d "{\"query\":\"$1\"}"; echo; } +VIN=$(curl -s $API -H "$H" -d '{"query":"{ wines(first: 1) { edges { node { id } } } }"}' | grep -o '"id":"[0-9]*"' | head -1 | cut -d'"' -f4) +echo "VIN=$VIN" +``` + +| Step | Expected | +|---|---| +| `q "mutation { setWineInList(wineId: \\\"$VIN\\\", list: WANT_TO_TRY, inList: true) { myLists } }"` | `["WANT_TO_TRY"]`. Running it again gives the same, and no second row in `user_wine` | +| The same with `list: FAVOURITE` | `["FAVOURITE","WANT_TO_TRY"]`, always in that order | +| The same with `list: TRIED` | `["FAVOURITE","TRIED"]`: «Har prøvd» took it off «Vil prøve» | +| `q "{ me { wines(list: FAVOURITE) { totalCount edges { node { name } } } } }"` | The wine, newest first | +| Put the wine on «Vil prøve» again, then `saveReview` on it | `myLists` has `TRIED` and not `WANT_TO_TRY`. After `deleteReview`, `TRIED` is still there | +| Add three favourites, then `setTopFavourites(wineIds: [...])` with them in a chosen order | `topFavourites` in that order | +| `setTopFavourites` with five wines, the same wine twice, or a wine that is not a favourite | `BAD_USER_INPUT`, and `topFavourites` is unchanged | +| Take a wine in the top 4 off the favourites | It leaves `topFavourites`. The others keep their order | +| The mutations without the cookie (leave out `-b /tmp/kk.jar`) | `UNAUTHENTICATED` | +| `SELECT list, wine_id, top_position FROM user_wine WHERE user_id = (SELECT id FROM app_user WHERE username = 'test_curl');` | The same as the API shows | + +## 6. The demo user + +| Step | Expected | +|---|---| +| `npm run db:seed:demo` in `backend/`, twice | «Demo user ready» both times, with no error | +| Log in as `demo` / `kork-og-krone` at `/konto` | Logged in | +| `q "{ me { topFavourites { name } wines(list: FAVOURITE) { totalCount } reviews { totalCount } } }"` as `demo` | Four wines in the top 4, six favourites and five reviews | + +## 7. Accessibility | Step | Expected | |---|---| @@ -114,7 +146,7 @@ Use the same method for every feature that stores data for a user: ## Removing test data ```sql -DELETE FROM app_user WHERE username LIKE 'test\_%'; -- sessions and reviews go with it +DELETE FROM app_user WHERE username LIKE 'test\_%'; -- sessions, reviews and lists go with it DELETE FROM review WHERE comment = 'Fra før innlogging'; ```