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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ 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 |
| Search | Done | Done | Ignores case and accents. Matches name, winery, region and grapes. Every word must match, in any order. 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. «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 |
Expand Down Expand Up @@ -460,7 +460,7 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a

### Some known issues

- Search matches the text as one phrase, so "noir pinot" finds nothing. Country is not part of the search text, because the country filter covers it.
- Country is not part of the search text, because the country filter covers it.
- The cursors in the API hold an offset, which is slower deep into large results. To be solved together with the larger dataset.
- The database and its user are still called `vinmonopolet` and `vinmonopolet_app`, from before we switched dataset. Renaming would mean everyone rebuilding their database, so we kept the names.
- Reviews from before login have no account and are shown as «Anonym student». The old `student` table they belong to will be removed later.
Expand Down
22 changes: 21 additions & 1 deletion backend/src/wine-query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
encodeCursor,
MAX_FACET_VALUES,
MAX_PAGE_SIZE,
MAX_SEARCH_WORDS,
TOP_RATED_MIN_COUNT,
} from './wine-query';

Expand Down Expand Up @@ -34,7 +35,26 @@ describe('buildWinesQuery', () => {
it('never puts the search text in the SQL itself', () => {
const query = buildWinesQuery({ search: "'; DROP TABLE wine; --" });
expect(query.listSql).not.toContain('DROP TABLE');
expect(query.listParams[0]).toBe("%'; drop table wine; --%");
expect(query.countParams).toEqual(["%';%", '%drop%', '%table%', '%wine;%', '%--%']);
});

it('requires each word of the search, in any order', () => {
const query = buildWinesQuery({ search: 'Noir pinot' });
expect(query.countSql).toContain('WHERE search_text ILIKE $1 AND search_text ILIKE $2');
expect(query.countParams).toEqual(['%noir%', '%pinot%']);
});

it('uses a repeated word once', () => {
expect(buildWinesQuery({ search: 'pinot Pinot' }).countParams).toEqual(['%pinot%']);
});

it('ignores a search with only spaces', () => {
expect(buildWinesQuery({ search: ' ' }).countSql).not.toContain('WHERE');
});

it(`uses at most ${MAX_SEARCH_WORDS} words`, () => {
const search = Array.from({ length: 30 }, (_, index) => `word${index}`).join(' ');
expect(buildWinesQuery({ search }).countParams).toHaveLength(MAX_SEARCH_WORDS);
});

it('makes the search case and accent insensitive', () => {
Expand Down
18 changes: 16 additions & 2 deletions backend/src/wine-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,17 @@ function escapeLike(text: string): string {
return text.replace(/[\\%_]/g, (char) => `\\${char}`);
}

/** More words than this are ignored, so one request cannot ask for hundreds of conditions. */
export const MAX_SEARCH_WORDS = 10;

/** The words of the search text, lowercase and without accents. A word is listed once. */
function toSearchWords(search: string | null | undefined): string[] {
const words = toSearchText(search ?? '')
.split(' ')
.filter(Boolean);
return [...new Set(words)].slice(0, MAX_SEARCH_WORDS);
}

/** 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);
Expand All @@ -83,8 +94,11 @@ function buildWhere(args: FilterArgs, params: unknown[], omit?: keyof WineFilter
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)}%`)}`);
// One condition per word, so the words can come in any order and with other words between
// them: «noir pinot» finds Pinot Noir. Each condition can use the trigram index.
for (const word of toSearchWords(args.search)) {
where.push(`search_text ILIKE ${param(`%${escapeLike(word)}%`)}`);
}

const filter: WineFilter = { ...args.filter, ...(omit && { [omit]: null }) };
if (filter.types?.length) where.push(`type = ANY(${param(filter.types)})`);
Expand Down