Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Kork & Krone

**Last updated:** 24 November 2026
**Last updated:** 24 November 2026
**Last updated:** 26 November 2026
**Submission:** 4 (working system, ready for feedback on every aspect)
**Status:** In progress. See [Status for submission 4](#status-for-submission-4).

Expand Down Expand Up @@ -135,7 +134,7 @@ This section describes what users can do. "Backend" means the API supports the f
| 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 |
| Wine lists: favourite, «Vil prøve» and «Har prøvd» | Done | Done | Stored per user and public, so they follow the user between browsers. Heart and bookmark on the wine cards, all three on the wine page, and each list on «Min side». The buttons change at once and go back with a message if saving fails. Visitors are sent to log in and back. «Har prøvd» takes a wine off «Vil prøve», and a saved review marks the wine as tried. A tried wine can still go back on «Vil prøve», and is then on both, as explained behind «Slik virker listene» on the wine page. See [«Vil prøve» and «Har prøvd»](#vil-prøve-and-har-prøvd). A «Vil prøve» list from before login moves to the user once. See [API](docs/api.md#wine-lists) |
| Top 4 favourites | Done | Done | Shown in its own frame on «Min side», with four numbered places. «Endre topp 4» chooses and orders them with buttons that work with the keyboard and a screen reader, without drag and drop |
| «Min side» | Done | Done | `/mine` with the top 4, the lists and the reviews, a page for each list at `/mine/favoritter`, `/mine/vil-prove` and `/mine/har-provd`, and `/mine/dommer`, newest or oldest first. Behind login |
| «Min side» | Done | Done | `/mine` with the top 4, the lists and the reviews, a page for each list at `/mine/favoritter`, `/mine/vil-prove` and `/mine/har-provd`, and `/mine/dommer`, newest or oldest first, with a search in the wine names and the comments. Behind login |
| 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 |

Expand Down Expand Up @@ -346,7 +345,7 @@ compress files at the time and the test was run over VPN. Turning on compression
| Level | Tools | What we test | Number of tests |
|---|---|---|---|
| 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 list buttons, «Min side», the list pages, the reviews page and «Endre topp 4», the cache rules for the lists, an expired session, loading, empty and error states, and axe on each component | 421 in 46 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 | 147 in 17 files (42 tests, 4 files skipped: they need a test database) |
| Unit (backend) | Vitest | Parsing of X-Wines CSV files, building SQL for search, filtering and sorting and for the search in a user's reviews, review validation, and passwords, sessions and rate limiting | 147 in 17 files (42 tests, 4 files 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, the wine lists (also after a reload, with login on the way, and the move of an old list), «Min side» from login to logout with the top 4 chosen with the keyboard, click targets of at least 44 × 44 px and visible focus on the main pages, and no axe violations (WCAG 2.1 AA) | 110 (6 skipped) |
| 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 |
| End-to-end with the backend | Playwright, desktop | The same pages against the real backend and a PostgreSQL test database (`TEST_DATABASE_URL`), with nothing stubbed: search, filter, sorting and «Last inn flere» on the 100 test wines, a new user with login, logout and a wrong password, a review from search to «Min side», a favourite that follows the user to another browser, and two users who review the same wine. See [API](docs/api.md#end-to-end-tests-with-the-backend) | 11 in 5 files |
Expand Down
7 changes: 1 addition & 6 deletions backend/src/lists/list-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// like wine-query.ts, so the sort orders and the cursor can be tested without PostgreSQL.
import { GraphQLError } from 'graphql';
import { decodeIdCursor, encodeIdCursor, MAX_INTEGER } from '../connection';
import { addParam } from '../wine-query';
import type { WineRow } from '../loaders';
import type { WineList } from './wine-lists';

Expand Down Expand Up @@ -100,12 +101,6 @@ export function decodeListCursor(
return { id, value };
}

/** Adds a value to params and returns its placeholder ($1, $2, ...). Never put user input in the SQL string. */
function addParam(params: unknown[], value: unknown): string {
params.push(value);
return `$${params.length}`;
}

/** The parts of a query on their own lines, leaving out the ones that are false. */
const lines = (...parts: (string | false)[]) => parts.filter(Boolean).join('\n');

Expand Down
42 changes: 19 additions & 23 deletions backend/src/resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ 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 { buildUserReviewsQuery, type ReviewOrder } from './review-query';
import {
buildFilterOptionsQueries,
buildWinesQuery,
Expand Down Expand Up @@ -206,34 +207,29 @@ export const resolvers = {

// User comes from auth/resolvers.ts. Fields that belong to other features are added here.
User: {
// By when the review was given, newest or oldest 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. The cursor is the id of the last review on the page, in both orders.
// By when the review was given, newest or oldest first, optionally only those that match a
// search. The SQL is built in review-query.ts. The cursor is the id of the last review on
// the page, in both orders.
async reviews(
user: { id: string },
args: { first?: number | null; after?: string | null; order?: 'NEWEST' | 'OLDEST' | null },
args: {
first?: number | null;
after?: string | null;
order?: ReviewOrder | null;
search?: string | null;
},
) {
const userId = Number(user.id);
const first = limitReviews(args.first, 10);
const afterId = decodeIdCursor(args.after);
// Fixed SQL for each order, never text from the request. The index review_user_id
// (user_id, id DESC) covers both, read forwards or backwards.
const page =
args.order === 'OLDEST'
? `SELECT * FROM review
WHERE user_id = $1 AND ($2::integer IS NULL OR id > $2)
ORDER BY id ASC
LIMIT $3`
: `SELECT * FROM review
WHERE user_id = $1 AND ($2::integer IS NULL OR id < $2)
ORDER BY id DESC
LIMIT $3`;
const query = buildUserReviewsQuery({
userId: Number(user.id),
order: args.order,
search: args.search,
first,
afterId: decodeIdCursor(args.after),
});
const [list, count] = await Promise.all([
pool.query<ReviewRow>(page, [userId, afterId, first + 1]),
pool.query<{ total: number }>(
'SELECT count(*)::int AS total FROM review WHERE user_id = $1',
[userId],
),
pool.query<ReviewRow>(query.listSql, query.listParams),
pool.query<{ total: number }>(query.countSql, query.countParams),
]);
return toConnection({
rows: list.rows,
Expand Down
105 changes: 100 additions & 5 deletions backend/src/review-api.db.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ const url = process.env.TEST_DATABASE_URL;
const SAVE = `mutation Save($input: ReviewInput!) { saveReview(input: $input) { id rating comment author } }`;
const DELETE = `mutation Delete($wineId: ID!) { deleteReview(wineId: $wineId) }`;
const MINE = `query Mine($wineId: ID!) { myReview(wineId: $wineId) { id rating comment author } }`;
const MY_REVIEWS = `query MyReviews($first: Int, $after: String, $order: ReviewOrder) {
me { reviews(first: $first, after: $after, order: $order) {
const MY_REVIEWS = `query MyReviews($first: Int, $after: String, $order: ReviewOrder, $search: String) {
me { reviews(first: $first, after: $after, order: $order, search: $search) {
totalCount
edges { node { rating wine { id } } }
pageInfo { hasNextPage endCursor }
Expand All @@ -44,20 +44,23 @@ describe.skipIf(!url)('reviews API (PostgreSQL)', () => {
// A wine of our own with an id far above the X-Wines ids, so the tests never touch real data.
const wineId = String(900_000_000 + Math.floor(Math.random() * 1_000_000));
const otherWineId = String(Number(wineId) + 1);
// A name with accents, for the search.
const accentWineId = String(Number(wineId) + 2);
const userIds: number[] = [];
const studentIds: number[] = [];

beforeAll(async () => {
await pool.query(
`INSERT INTO wine (id, name, type, search_text)
VALUES ($1, 'Testvin', 'Red', 'testvin'), ($2, 'Testvin 2', 'White', 'testvin 2')`,
[wineId, otherWineId],
VALUES ($1, 'Testvin', 'Red', 'testvin'), ($2, 'Testvin 2', 'White', 'testvin 2'),
($3, 'Château Rosé', 'Rosé', 'chateau rose')`,
[wineId, otherWineId, accentWineId],
);
});

// Reviews go with the wine and the users (ON DELETE CASCADE).
afterAll(async () => {
await pool.query('DELETE FROM wine WHERE id = ANY($1)', [[wineId, otherWineId]]);
await pool.query('DELETE FROM wine WHERE id = ANY($1)', [[wineId, otherWineId, accentWineId]]);
await pool.query('DELETE FROM app_user WHERE id = ANY($1)', [userIds]);
await pool.query('DELETE FROM student WHERE id = ANY($1)', [studentIds]);
await pool.end();
Expand Down Expand Up @@ -273,6 +276,98 @@ describe.skipIf(!url)('reviews API (PostgreSQL)', () => {
expect(codeOf(await per.request(MY_REVIEWS, { order: 'BEST' }))).toBe('BAD_USER_INPUT');
});

describe('with a search', () => {
/** Three reviews by a new user, oldest first: one per wine, two with a comment. */
async function threeReviews(as: string) {
const browser = await createBrowser(as);
await browser.request(SAVE, save(4, 'Fyldig og rund, perfekt til LAM.'));
await browser.request(SAVE, {
input: { wineId: otherWineId, rating: 3, comment: '100% verdt det, til fisk' },
});
await browser.request(SAVE, { input: { wineId: accentWineId, rating: 5 } });
return browser;
}
const wineIdsOf = (page: Page) => page.edges.map((edge) => edge.node.wine.id);

it('finds a review by a word in its comment, ignoring case', async () => {
const kim = await threeReviews('kim');
const page = pageOf(await kim.request(MY_REVIEWS, { search: 'lam' }));
expect(wineIdsOf(page)).toEqual([wineId]);
expect(page.totalCount).toBe(1);
});

it('finds a review by the wine name, ignoring accents both ways', async () => {
const liv = await threeReviews('liv');
for (const search of ['chateau rose', 'CHÂTEAU', 'rosé']) {
expect(wineIdsOf(pageOf(await liv.request(MY_REVIEWS, { search })))).toEqual([
accentWineId,
]);
}
});

it('needs every word, in the name or the comment, in any order', async () => {
const mia = await threeReviews('mia');
const ids = async (search: string) =>
wineIdsOf(pageOf(await mia.request(MY_REVIEWS, { search })));

expect(await ids('rund fyldig')).toEqual([wineId]);
// One word in the name («Testvin 2»), one in the comment.
expect(await ids('testvin fisk')).toEqual([otherWineId]);
expect(await ids('lam fisk')).toEqual([]);
// Both «til» comments, newest first.
expect(await ids('til')).toEqual([otherWineId, wineId]);
});

it('matches % and _ literally', async () => {
const nils = await threeReviews('nils');
expect(wineIdsOf(pageOf(await nils.request(MY_REVIEWS, { search: '100%' })))).toEqual([
otherWineId,
]);
expect(pageOf(await nils.request(MY_REVIEWS, { search: '_' })).totalCount).toBe(0);
});

it('lists every review for a blank search', async () => {
const oda = await threeReviews('oda');
expect(pageOf(await oda.request(MY_REVIEWS, { search: ' ' })).totalCount).toBe(3);
});

it('never finds the reviews of another user', async () => {
await threeReviews('pia');
const rolf = await createBrowser('rolf');
await rolf.request(SAVE, { input: { wineId: otherWineId, rating: 2 } });

const page = pageOf(await rolf.request(MY_REVIEWS, { search: 'lam' }));
expect(page).toEqual({
totalCount: 0,
edges: [],
pageInfo: { hasNextPage: false, endCursor: null },
});
});

it('pages through the hits in both orders, and counts only hits', async () => {
const sol = await threeReviews('sol');

for (const [order, expected] of [
['NEWEST', [otherWineId, wineId]],
['OLDEST', [wineId, otherWineId]],
] as const) {
const first = pageOf(await sol.request(MY_REVIEWS, { search: 'til', order, first: 1 }));
expect(first.totalCount).toBe(2);
expect(first.pageInfo.hasNextPage).toBe(true);
const second = pageOf(
await sol.request(MY_REVIEWS, {
search: 'til',
order,
first: 1,
after: first.pageInfo.endCursor,
}),
);
expect([...wineIdsOf(first), ...wineIdsOf(second)]).toEqual(expected);
expect(second.pageInfo.hasNextPage).toBe(false);
}
});
});

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(
Expand Down
71 changes: 71 additions & 0 deletions backend/src/review-query.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { describe, expect, it } from 'vitest';
import { buildUserReviewsQuery } from './review-query';
import { MAX_SEARCH_WORDS } from './wine-query';

// Which reviews a search finds is tested against PostgreSQL in review-api.db.test.ts. These tests
// cover what can be checked without a database: the SQL that is built and its parameters.

const base = { userId: 7, first: 10, afterId: null };

describe('buildUserReviewsQuery', () => {
it('lists every review of the user, newest first, without a search', () => {
const query = buildUserReviewsQuery(base);
expect(query.listSql).toContain('WHERE review.user_id = $1');
expect(query.listSql).toContain('ORDER BY review.id DESC');
expect(query.listSql).not.toContain('JOIN');
expect(query.listParams).toEqual([7, 11]);
expect(query.countParams).toEqual([7]);
});

it('pages after the cursor in either order, and the count ignores the cursor', () => {
const newest = buildUserReviewsQuery({ ...base, afterId: 40 });
expect(newest.listSql).toContain('review.id < $2');
const oldest = buildUserReviewsQuery({ ...base, order: 'OLDEST', afterId: 40 });
expect(oldest.listSql).toContain('review.id > $2');
expect(oldest.listSql).toContain('ORDER BY review.id ASC');
expect(oldest.countSql).not.toContain('review.id');
});

it('treats a blank search as no search', () => {
expect(buildUserReviewsQuery({ ...base, search: ' ' })).toEqual(buildUserReviewsQuery(base));
});

it('needs every word in the wine name or the comment, folded like the search words', () => {
const query = buildUserReviewsQuery({ ...base, search: 'Chianti LAM' });
expect(query.listParams).toEqual([7, '%chianti%', '%lam%', 11]);
expect(query.listSql).toContain('(folded.wine_name LIKE $2 OR folded.comment LIKE $2)');
expect(query.listSql).toContain('(folded.wine_name LIKE $3 OR folded.comment LIKE $3)');
// The page and the count filter the same way.
expect(query.countSql).toContain('folded.comment LIKE $3');
expect(query.countParams).toEqual([7, '%chianti%', '%lam%']);
});

it('folds the search words: no accents, lowercase, each word once', () => {
expect(buildUserReviewsQuery({ ...base, search: 'Rosé ROSE rosé' }).listParams).toEqual([
7,
'%rose%',
11,
]);
});

it('matches % and _ in the search literally', () => {
expect(buildUserReviewsQuery({ ...base, search: '100% a_b' }).listParams).toEqual([
7,
'%100\\%%',
'%a\\_b%',
11,
]);
});

it('never puts the search text in the SQL itself', () => {
const query = buildUserReviewsQuery({ ...base, search: "x'; DROP TABLE review; --" });
expect(query.listSql).not.toContain('DROP');
expect(query.countSql).not.toContain('DROP');
});

it('uses at most MAX_SEARCH_WORDS words', () => {
const search = Array.from({ length: MAX_SEARCH_WORDS + 5 }, (_, i) => `ord${i}`).join(' ');
const { countParams } = buildUserReviewsQuery({ ...base, search });
expect(countParams).toHaveLength(1 + MAX_SEARCH_WORDS);
});
});
Loading