Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ This section describes what users can do. "Backend" means the API supports the f
|---|---|---|---|
| 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 | 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 |
| Sorting | Done | Done | Top rated, most rated, name and alcohol. Always sorts the whole result, not only the loaded page. «Best vurdert» puts wines with at least 50 ratings first, so a 5.0 from five people does not top the list |
| Pagination | Done | Done | Pages behind an opaque cursor that holds an offset. 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=&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 |
Expand Down Expand Up @@ -165,7 +165,7 @@ Each row explains what we chose, why, and what else we considered. Added as the
| Database changes | Migrations with node-pg-migrate | Everyone and the VM get the same database by running one command, without deleting and rebuilding it | Editing a single schema file by hand |
| Pagination | GraphQL connection with an opaque cursor that holds an offset. Pages are merged in the Apollo cache | Simple, and works with every sort order. The frontend never reads the cursor, so we can switch to keyset pagination later without changing it | Keyset pagination: faster deep into large results, but harder to combine with many sort orders |
| Search, filtering and sorting | In the database | Scales to large datasets. The frontend never loads the whole catalogue | Filtering in the browser |
| Rating average | Stored on the wine and recalculated when a review is saved or deleted | Sorting and filtering by rating never has to count millions of rows | Calculating the average for every query |
| «Best vurdert» | Wines with at least 50 ratings first, then the rest, each part by average and then number of ratings | A 5.0 from five people topped the list before. 50 is just under the median (about 58), so more than half the catalogue (56 333 wines) qualifies. Wines under the limit are not hidden, so the number of hits is the same for every sort order. An index follows the same order, so the first page is fast | A weighted average (as on IMDb): fairer, but needs its own stored column to be fast. Hiding wines under the limit |
| List buttons | `myLists` asked for with each wine, read from the cache with `useFragment`, and changed with an optimistic answer | A page of wines needs no extra request, every button for a wine agrees, and a click shows at once | Fetching the lists of each wine separately, or waiting for the API before the button changes |
| Top 4 editor | Buttons to move, add and take out, with a live region and focus kept on the button | Works the same with a keyboard, a screen reader, a switch and a finger, and is simple to test | Drag and drop, which needs a second way to do the same for keyboard and screen reader users |
| Expired session | An Apollo link that fetches `me` again when the API says `UNAUTHENTICATED` | The whole page shows at once that the user is logged out, wherever the error came from | Checking for the error in each feature |
Expand Down
13 changes: 13 additions & 0 deletions backend/migrations/1795525601595_top-rated-min-count.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
-- Up Migration

-- «Best vurdert» now puts wines with at least 50 ratings first (TOP_RATED_MIN_COUNT in
-- src/wine-query.ts). The index follows the new ORDER BY exactly, so PostgreSQL reads the first
-- page straight from the index instead of sorting every wine. Keep the number the same as in the code.
DROP INDEX IF EXISTS wine_top_rated;
CREATE INDEX wine_top_rated
ON wine ((community_count >= 50) DESC, community_avg DESC NULLS LAST, community_count DESC, id);

-- Down Migration

DROP INDEX IF EXISTS wine_top_rated;
CREATE INDEX wine_top_rated ON wine (community_avg DESC NULLS LAST, community_count DESC, id);
17 changes: 15 additions & 2 deletions backend/src/wine-query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,30 @@ import {
encodeCursor,
MAX_FACET_VALUES,
MAX_PAGE_SIZE,
TOP_RATED_MIN_COUNT,
} from './wine-query';

describe('buildWinesQuery', () => {
it('returns all wines sorted by top rating when there are no arguments', () => {
const query = buildWinesQuery({});
expect(query.listSql).not.toContain('WHERE');
expect(query.listSql).toContain('ORDER BY community_avg DESC NULLS LAST');
expect(query.first).toBe(24);
expect(query.listSql).toContain(
`ORDER BY (community_count >= ${TOP_RATED_MIN_COUNT}) DESC, community_avg DESC NULLS LAST`,
);
expect(query.offset).toBe(0);
});

it('puts wines with few ratings after the others in «Best vurdert», without hiding them', () => {
const query = buildWinesQuery({ sort: 'TOP_RATED' });
expect(query.listSql).toContain(`(community_count >= ${TOP_RATED_MIN_COUNT}) DESC`);
// The limit only changes the order, never which wines match.
expect(query.countSql).not.toContain('community_count');
// The other sort orders are unchanged.
expect(buildWinesQuery({ sort: 'MOST_RATED' }).listSql).not.toContain(
`>= ${TOP_RATED_MIN_COUNT}`,
);
});

it('never puts the search text in the SQL itself', () => {
const query = buildWinesQuery({ search: "'; DROP TABLE wine; --" });
expect(query.listSql).not.toContain('DROP TABLE');
Expand Down
10 changes: 9 additions & 1 deletion backend/src/wine-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,17 @@ 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;

/**
* «Best vurdert» puts wines with at least this many ratings first, so a 5.0 from five people
* does not beat a 4.9 from hundreds. Wines with fewer ratings are not hidden, only sorted after
* the others, so the number of hits stays the same for every sort order. Median is about 58.
* The index wine_top_rated uses the same number: change the migration too if this changes.
*/
export const TOP_RATED_MIN_COUNT = 50;

// 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',
TOP_RATED: `(community_count >= ${TOP_RATED_MIN_COUNT}) DESC, community_avg DESC NULLS LAST, community_count DESC, id`,
MOST_RATED: 'community_count DESC, community_avg DESC NULLS LAST, id',
NAME_ASC: 'name ASC, id',
NAME_DESC: 'name DESC, id',
Expand Down
2 changes: 2 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ https://doi.org/10.3390/bdcc7010020
## Queries

- `wines(search, filter, sort, first, after)`: search, filter and sort the whole catalog.
`TOP_RATED` (the default) puts wines with at least 50 ratings first, then the rest, each part by
average. The limit is `TOP_RATED_MIN_COUNT` in `backend/src/wine-query.ts`.
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.
Expand Down