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
22 changes: 11 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ Submission 3 should be the first complete prototype, with search, browsing, sort
| Backend running on the VM | Done | Started with `nohup`, see [VM guide](docs/vm.md) |
| Apollo Client in the frontend | Done | |
| Search page with results | Done | Search with debounce, number of hits and "Last inn flere" at `/sok` |
| Filtering and sorting in the user interface | Next | The API and URL filters work, but the panel is missing |
| Filtering and sorting in the user interface | Done | Filter panel, active filters and sorting on `/sok`. Needs the new backend on the VM |
| Wine detail page | Done | Facts, food pairing and rating at `/vin/:id`. Student reviews are added with the reviews feature |
| Student reviews (stored in the database) | Planned | |
| Larger dataset on the VM | Planned | |
Expand Down Expand Up @@ -99,10 +99,10 @@ This section describes what users can do. "Backend" means the API supports the f
| Feature | Backend | UI | Description |
|---|---|---|---|
| Search | Done | Done | Ignores case and accents. Matches name, winery, region and grapes as one phrase. Waits 300 ms after the last key press |
| Filtering | Done | Planned | Type, country, grapes, food pairing, minimum rating and alcohol range. Shows the number of wines for each option |
| Sorting | Done | Planned | Top rated, most rated, name and alcohol. Always sorts the whole result, not only the loaded page |
| Filtering | Done | Done | Type, country, grapes, food pairing, minimum rating and alcohol range. Several values can be selected. The counts follow the search and the other filters. On small screens the filters open in a dialog |
| Sorting | Done | Done | Top rated, most rated, name and alcohol. Always sorts the whole result, not only the loaded page |
| Pagination | Done | Done | Cursor-based. The user loads more results with a button, not with infinite scroll. Focus moves to the first new wine |
| Search state in the URL | Not needed | Done | `?q=&type=&land=&drue=&mat=&sort=`. Survives reloads. Typing replaces the history entry, so the back button leaves the search instead of stepping through every word |
| Search state in the URL | Not needed | Done | `?q=&type=&land=&drue=&mat=&vurdering=&alkohol=&sort=`. Survives reloads. Typing replaces the history entry, so the back button leaves the search instead of stepping through every word |
| 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 are planned |
| Student reviews | Planned | Planned | Die roll from 1 to 6 and an optional comment, stored in PostgreSQL, the new rating is shown at once without a reload (Apollo cache update) |
| Wishlist ("Vil prøve") | Planned | Done, stored in the browser | Moves to the backend when users and reviews are in place |
Expand Down Expand Up @@ -137,6 +137,8 @@ Each row explains what we chose, why, and what else we considered. Added as the
| Pagination | Cursor-based, pages merged in the Apollo cache | Stable when sorting. No duplicates or gaps when new data is added | Offset-based |
| Search, filtering and sorting | In the database | Scales to large datasets. The frontend never loads the whole catalogue | Filtering in the browser |
| Search state flow | Field text in React state, debounced into the URL, and the query reads only the URL | One source of truth for the search, so reload, shared links and the back button all give the same result | Sending a request directly from the input |
| Filter panel on small screens | Native `<dialog>` with `showModal()` | The browser handles focus trapping, Escape and returning focus, with no extra JavaScript | A dialog library |
| Filter counts | One count query per group that leaves out the group's own filter | The user can see what each choice gives before choosing, and values can be combined | Fixed counts for the whole catalogue |
| Testing | Vitest, React Testing Library, Playwright, axe | Vitest shares configuration with Vite. Playwright tests real browsers, also on mobile | Jest, Cypress |
| Deployment | Apache serves static files, the backend runs with `nohup` | Matches the course VM | systemd service (possible improvement) |

Expand Down Expand Up @@ -198,10 +200,8 @@ Our goal is WCAG 2.1 level AA. We design for users with reduced vision, hearing,

### Some known gaps

- The filter panel is not built yet, so it is not tested.
- We have not tested with a screen reader yet.
- eslint-plugin-jsx-a11y is not set up yet.
- The filter panel on mobile will need a dialog with correct focus handling. This is planned.

## Sustainability

Expand Down Expand Up @@ -229,7 +229,7 @@ We follow the principle from the course: measure, set a budget and show the numb

| Metric | Budget | Measured | Date | How we measure |
|---|---|---|---|---|
| JavaScript on the landing page (gzip) | Less than 150 kB | 154,89 kB (over budget after adding Apollo Client) | 7 Nov 2026 | Sum of the gzip sizes from `npm run build` for the files the landing page loads |
| JavaScript on the landing page (gzip) | Less than 150 kB | 155,05 kB (over budget after adding Apollo Client) | 7 Nov 2026 | Sum of the gzip sizes from `npm run build` for the files the landing page loads |
| Data transferred when loading the landing page | Less than 300 kB | Not measured yet | | Chrome DevTools, Network tab, cache disabled, on the VM |
| Data transferred in a fixed search scenario | Less than 500 kB | Not measured yet | | Same method. Needs the search page |
| Lighthouse (mobile) | Performance at least 90, accessibility 100 | Performance 39, accessibility 100, best practices 100, SEO 100 | 30 Oct 2026 | Lighthouse in Chrome DevTools, incognito, against the VM |
Expand All @@ -243,14 +243,14 @@ and because the test was run over VPN. These are the "before" numbers. We will m

| 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, loading, empty and error states, and axe on each component | 188 |
| 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, loading, empty and error states, and axe on each component | 233 |
| Unit (backend) | Vitest | Parsing of X-Wines CSV files, and building SQL for search, filtering and sorting | 2 test files |
| 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, load more, reload, back button, from search to wine and back, no hits, wine not found, API errors, keyboard use, reflow at 320 px, and no axe violations (WCAG 2.1 AA) | 40 (20 tests in 2 browser projects) |
| 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 | Not set up yet | Resolvers against a test database: search, filtering, sorting and pagination | Planned |

Counted on 7 November 2026.

**Coverage (frontend, 7 November 2026):** lines 98.58 %, branches 82.39 %, functions 95.9 %, statements 89.18 %.
**Coverage (frontend, 7 November 2026):** lines 98.93 %, branches 85.3 %, functions 97.14 %, statements 90.97 %.

Vitest enforces a minimum of 80 % for lines, functions and statements and 75 % for branches (`vitest.config.ts`).
We will add the missing tests before raising the limits further, and we do not lower the limits to make the run pass.
Expand Down Expand Up @@ -340,7 +340,7 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a

1. [x] Add Apollo Client to the frontend, with the endpoint `${import.meta.env.BASE_URL}graphql`.
2. [x] Search page: search field with debounce, list of results, number of hits, "Last inn flere", and empty and error states.
3. [ ] Filter panel with counts from `filterOptions`, and sorting. All choices stored in the URL.
3. [x] Filter panel with counts from `filterOptions`, and sorting. All choices stored in the URL.
4. [x] Connect the landing page to the backend.
5. [x] Wine detail page.
6. [ ] Start the backend on the VM and load the dataset.
Expand Down
35 changes: 25 additions & 10 deletions backend/src/resolvers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
// Resolvers: the functions that fetch data for each field in the schema.
import { pool } from './db';
import { buildWinesQuery, encodeCursor, type WinesArgs } from './wine-query';
import {
buildFilterOptionsQueries,
buildWinesQuery,
encodeCursor,
type FilterArgs,
type WinesArgs,
} from './wine-query';

// A row from the wine table, as returned by pg.
interface WineRow {
Expand Down Expand Up @@ -46,6 +52,14 @@ function toWine(row: WineRow) {
};
}

async function filterOptions(
args: FilterArgs,
group: keyof ReturnType<typeof buildFilterOptionsQueries>,
) {
const { sql, params } = buildFilterOptionsQueries(args)[group];
return (await pool.query(sql, params)).rows;
}

export const resolvers = {
Query: {
async wines(_parent: unknown, args: WinesArgs) {
Expand Down Expand Up @@ -78,15 +92,16 @@ export const resolvers = {
return result.rows[0] ? toWine(result.rows[0]) : null;
},

async filterOptions() {
const [types, countries] = await Promise.all([
pool.query(`SELECT type AS value, type AS label, count(*)::int AS count
FROM wine GROUP BY type ORDER BY count DESC, type`),
pool.query(`SELECT country_code AS value, max(country) AS label, count(*)::int AS count
FROM wine WHERE country_code IS NOT NULL
GROUP BY country_code ORDER BY count DESC, label`),
]);
return { types: types.rows, countries: countries.rows };
// The counts are in the fields below, so a query only pays for the groups it asks for.
filterOptions(_parent: unknown, args: FilterArgs) {
return args;
},
},

FilterOptions: {
types: (args: FilterArgs) => filterOptions(args, 'types'),
countries: (args: FilterArgs) => filterOptions(args, 'countries'),
grapes: (args: FilterArgs) => filterOptions(args, 'grapes'),
harmonize: (args: FilterArgs) => filterOptions(args, 'harmonize'),
},
};
8 changes: 6 additions & 2 deletions backend/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ export const typeDefs = `#graphql
type FilterOptions {
types: [FilterOption!]!
countries: [FilterOption!]!
"The most common grapes."
grapes: [FilterOption!]!
"The most common food pairings."
harmonize: [FilterOption!]!
}

type Query {
Expand All @@ -82,7 +86,7 @@ export const typeDefs = `#graphql

wine(id: ID!): Wine

"Values for the filter panel, with the number of wines for each value."
filterOptions: FilterOptions!
"Values for the filter panel. The counts follow the search and the filters in the other groups."
filterOptions(search: String, filter: WineFilter): FilterOptions!
}
`;
65 changes: 64 additions & 1 deletion backend/src/wine-query.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { describe, expect, it } from 'vitest';
import { buildWinesQuery, decodeCursor, encodeCursor, MAX_PAGE_SIZE } from './wine-query';
import {
buildFilterOptionsQueries,
buildWinesQuery,
decodeCursor,
encodeCursor,
MAX_FACET_VALUES,
MAX_PAGE_SIZE,
} from './wine-query';

describe('buildWinesQuery', () => {
it('returns all wines sorted by top rating when there are no arguments', () => {
Expand Down Expand Up @@ -50,6 +57,62 @@ describe('buildWinesQuery', () => {
});
});

describe('buildFilterOptionsQueries', () => {
const args = {
search: 'pinot',
filter: {
types: ['Red'],
countryCodes: ['FR'],
grapes: ['Merlot'],
harmonize: ['Beef'],
minRating: 4,
},
};

it('counts all wines when there is no search or filter', () => {
const { types } = buildFilterOptionsQueries({});
expect(types.sql).not.toContain('WHERE');
expect(types.params).toEqual([]);
});

it('leaves out its own filter, so the other values in the group still have a count', () => {
const { types, countries, grapes, harmonize } = buildFilterOptionsQueries(args);
expect(types.params).toEqual(['%pinot%', ['FR'], ['Merlot'], ['Beef'], 4]);
expect(countries.params).toEqual(['%pinot%', ['Red'], ['Merlot'], ['Beef'], 4]);
expect(grapes.params).toEqual(['%pinot%', ['Red'], ['FR'], ['Beef'], 4]);
expect(harmonize.params).toEqual(['%pinot%', ['Red'], ['FR'], ['Merlot'], 4]);
});

it('keeps the search and the other filters', () => {
const { types } = buildFilterOptionsQueries(args);
expect(types.sql).toContain('search_text ILIKE $1');
expect(types.sql).toContain('country_code = ANY($2)');
expect(types.sql).not.toContain('type = ANY');
});

it('leaves out wines without a country', () => {
expect(buildFilterOptionsQueries({}).countries.sql).toContain('WHERE country_code IS NOT NULL');
expect(buildFilterOptionsQueries(args).countries.sql).toContain('AND country_code IS NOT NULL');
});

it('splits the lists of grapes and food into one row per value', () => {
const { grapes, harmonize } = buildFilterOptionsQueries({});
expect(grapes.sql).toContain('unnest(grapes)');
expect(harmonize.sql).toContain('unnest(harmonize)');
});

it('limits the number of grapes and food values, since there can be thousands', () => {
const { grapes, harmonize } = buildFilterOptionsQueries({});
expect(grapes.sql).toContain(`LIMIT ${MAX_FACET_VALUES}`);
expect(harmonize.sql).toContain(`LIMIT ${MAX_FACET_VALUES}`);
});

it('never puts the search text in the SQL itself', () => {
const { grapes } = buildFilterOptionsQueries({ search: "'; DROP TABLE wine; --" });
expect(grapes.sql).not.toContain('DROP TABLE');
});
});

describe('cursor', () => {
it('round-trips an offset', () => {
expect(decodeCursor(encodeCursor(48))).toBe(48);
Expand Down
66 changes: 56 additions & 10 deletions backend/src/wine-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,22 @@ export interface WineFilter {
maxAbv?: number | null;
}

export interface WinesArgs {
export interface FilterArgs {
search?: string | null;
filter?: WineFilter | null;
}

export interface WinesArgs extends FilterArgs {
sort?: WineSort | null;
first?: number | null;
after?: string | null;
}

export const MAX_PAGE_SIZE = 50;

// Enough for the filter panel. The Full dataset has far more grapes than anyone scrolls through.
export const MAX_FACET_VALUES = 40;

// Only these ORDER BY clauses can ever reach the database. "id" last makes the order stable.
const ORDER_BY: Record<WineSort, string> = {
TOP_RATED: 'community_avg DESC NULLS LAST, community_count DESC, id',
Expand Down Expand Up @@ -53,19 +59,21 @@ function escapeLike(text: string): string {
return text.replace(/[\\%_]/g, (char) => `\\${char}`);
}

export function buildWinesQuery(args: WinesArgs) {
const where: string[] = [];
const params: unknown[] = [];
// Adds a value to params and returns its placeholder ($1, $2, ...). Never put user input in the SQL string.
const param = (value: unknown) => {
/** 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 search and the filters as WHERE conditions. `omit` leaves out one filter, for the counts. */
function buildWhere(args: FilterArgs, params: unknown[], omit?: keyof WineFilter): string[] {
const where: string[] = [];
const param = (value: unknown) => addParam(params, value);

const search = toSearchText(args.search ?? '');
if (search) where.push(`search_text ILIKE ${param(`%${escapeLike(search)}%`)}`);

const filter = args.filter ?? {};
const filter: WineFilter = { ...args.filter, ...(omit && { [omit]: null }) };
if (filter.types?.length) where.push(`type = ANY(${param(filter.types)})`);
if (filter.countryCodes?.length) where.push(`country_code = ANY(${param(filter.countryCodes)})`);
// && means "the lists have at least one value in common".
Expand All @@ -74,8 +82,46 @@ export function buildWinesQuery(args: WinesArgs) {
if (filter.minRating != null) where.push(`community_avg >= ${param(filter.minRating)}`);
if (filter.minAbv != null) where.push(`abv >= ${param(filter.minAbv)}`);
if (filter.maxAbv != null) where.push(`abv <= ${param(filter.maxAbv)}`);
return where;
}

const toWhereSql = (where: string[]) => (where.length ? `WHERE ${where.join(' AND ')}` : '');

/**
* One count query per filter group, for the numbers in the filter panel. Each query leaves
* out the group's own filter: with "Red" selected, "White" still shows what it would add.
*/
export function buildFilterOptionsQueries(args: FilterArgs) {
const query = (omit: keyof WineFilter, build: (where: string[]) => string) => {
const params: unknown[] = [];
return { sql: build(buildWhere(args, params, omit)), params };
};
// Grapes and food are lists on each wine, so each value in a list becomes its own row.
const listValues = (column: 'grapes' | 'harmonize') => (where: string[]) =>
`SELECT value, value AS label, count(*)::int AS count
FROM wine CROSS JOIN LATERAL unnest(${column}) AS value ${toWhereSql(where)}
GROUP BY value ORDER BY count DESC, value LIMIT ${MAX_FACET_VALUES}`;

const whereSql = where.length ? `WHERE ${where.join(' AND ')}` : '';
return {
types: query(
'types',
(where) => `SELECT type AS value, type AS label, count(*)::int AS count
FROM wine ${toWhereSql(where)} GROUP BY type ORDER BY count DESC, type`,
),
countries: query(
'countryCodes',
(where) => `SELECT country_code AS value, max(country) AS label, count(*)::int AS count
FROM wine ${toWhereSql([...where, 'country_code IS NOT NULL'])}
GROUP BY country_code ORDER BY count DESC, label`,
),
grapes: query('grapes', listValues('grapes')),
harmonize: query('harmonize', listValues('harmonize')),
};
}

export function buildWinesQuery(args: WinesArgs) {
const params: unknown[] = [];
const whereSql = toWhereSql(buildWhere(args, params));
const orderBy = ORDER_BY[args.sort ?? 'TOP_RATED'];
if (!orderBy) throw new Error('Invalid sort.');

Expand All @@ -85,7 +131,7 @@ export function buildWinesQuery(args: WinesArgs) {

// Fetch one extra row to know if there is a next page.
const listSql = `SELECT * FROM wine ${whereSql} ORDER BY ${orderBy}
LIMIT ${param(first + 1)} OFFSET ${param(offset)}`;
LIMIT ${addParam(params, first + 1)} OFFSET ${addParam(params, offset)}`;
const countSql = `SELECT count(*)::int AS total FROM wine ${whereSql}`;

return { listSql, listParams: params, countSql, countParams, first, offset };
Expand Down
5 changes: 4 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ https://doi.org/10.3390/bdcc7010020
Returns `totalCount`, `edges { cursor node }` and `pageInfo { hasNextPage endCursor }`.
Pass `pageInfo.endCursor` as `after` to load the next page. `first` is at most 50.
- `wine(id)`: one wine, or `null` if it does not exist.
- `filterOptions`: values for the filter panel with the number of wines per value.
- `filterOptions(search, filter)`: values for the filter panel with the number of wines per value.
The counts follow the search and the filters in the other groups, but not the group's own filter:
with `Red` selected, `White` still shows what it would add. `grapes` and `harmonize` return the 40
most common values. Only the requested groups are counted.

Search is case and accent insensitive and matches name, winery, region and grapes.
Several values in one filter list mean OR. Search and different filters are combined with AND.
Expand Down
Loading