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
2 changes: 1 addition & 1 deletion backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ When the tests are done, Postgres is stopped and the folder is deleted. As a saf
refuses to reset a database whose name doesn't end with `_test`.

The tests cover searching, filtering, sorting and paging through books, getting
one book, the lists of filter options, and adding and removing favorites (also
one book, the lists of filter options and how they are counted for a search, and adding and removing favorites (also
that users must be logged in, and only see their own favorites).

> [!NOTE]
Expand Down
118 changes: 118 additions & 0 deletions backend/src/schema/books/bookFilter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import {
and,
eq,
exists,
gte,
ilike,
lte,
or,
sql,
type SQL,
} from "drizzle-orm";
import { GraphQLError } from "graphql/error";
import { db } from "~/db";
import { bookGenres, books, bookToGenres } from "~/db/schema";
import type { QuerysearchBooksArgs } from "~/schema/types.generated";

// The arguments that decide which books match a search. searchBooks and
// bookFacets take the same ones, so the filter options always agree with the
// search results
type BookFilterArgs = Omit<
QuerysearchBooksArgs,
"limit" | "offset" | "sortBy" | "sortDirection"
>;

// The filters that have their own list of options in bookFacets
type FacetName = "genres" | "language" | "bookFormat";

const MAX_GENRES = 15;
const MAX_TEXT_LENGTH = 200;

function assertBookFilterArgs(args: BookFilterArgs) {
if (args.genres && args.genres.length > MAX_GENRES) {
throw new GraphQLError(`You may only select up to ${MAX_GENRES} genres.`, {
extensions: { code: "BAD_USER_INPUT" },
});
}

const texts = [args.query, args.series, args.author, args.publisher];
if (texts.some((text) => text && text.length > MAX_TEXT_LENGTH)) {
throw new GraphQLError(
`Search text may only be up to ${MAX_TEXT_LENGTH} characters.`,
{ extensions: { code: "BAD_USER_INPUT" } },
);
}
}

/**
* Builds the WHERE condition for the books that match the arguments, or
* undefined if nothing is filtered.
*
* `ignore` leaves out one filter. bookFacets uses it to count the options of a
* filter as if that filter wasn't set, so the user can still switch to another
* option.
*/
function buildBookFilter(
args: BookFilterArgs,
{ ignore }: { ignore?: FacetName } = {},
): SQL | undefined {
const conditions: SQL[] = [];

// <% is the word similarity operator using the pg_trgm extension
if (args.query) {
const queryFilter = args.fuzzy
? or(
sql`${args.query} <% ${books.title}`,
sql`${args.query} <% ${books.author}`,
)
: or(
ilike(books.title, `%${args.query}%`),
ilike(books.author, `%${args.query}%`),
);
if (queryFilter) conditions.push(queryFilter);
}

if (args.series) conditions.push(ilike(books.series, `%${args.series}%`));
if (args.author) conditions.push(ilike(books.author, `%${args.author}%`));
if (args.language && ignore !== "language")
conditions.push(eq(books.language, args.language));
if (args.bookFormat && ignore !== "bookFormat")
conditions.push(eq(books.bookFormat, args.bookFormat));
if (args.publisher)
conditions.push(ilike(books.publisher, `%${args.publisher}%`));
if (args.minPages != null) conditions.push(gte(books.pages, args.minPages));
if (args.maxPages != null) conditions.push(lte(books.pages, args.maxPages));
if (args.minRatings != null)
conditions.push(gte(books.numRatings, args.minRatings));

// A book matches if it has any of the selected genres
const genreConditions: SQL[] = [];

for (const genre of ignore === "genres" ? [] : (args.genres ?? [])) {
genreConditions.push(
exists(
db
.select()
.from(bookToGenres)
.innerJoin(bookGenres, eq(bookGenres.id, bookToGenres.genreId))
.where(
and(eq(bookToGenres.bookId, books.id), eq(bookGenres.genre, genre)),
),
),
);
}

if (genreConditions.length > 0) {
const genreFilter = or(...genreConditions);
if (genreFilter) conditions.push(genreFilter);
}

return conditions.length > 0 ? and(...conditions) : undefined;
}

export {
assertBookFilterArgs,
buildBookFilter,
type BookFilterArgs,
type FacetName,
};
69 changes: 69 additions & 0 deletions backend/src/schema/books/facets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { and, asc, count, desc, eq, isNotNull, type SQL } from "drizzle-orm";
import { db } from "~/db";
import { bookGenres, books, bookToGenres } from "~/db/schema";
import type { FacetValue } from "~/schema/types.generated";

// Every list is ordered by the number of books, and then alphabetically

async function countGenres(filter?: SQL): Promise<FacetValue[]> {
const bookCount = count(bookToGenres.bookId);

// Without a filter, every genre is counted, so the books table isn't needed
const rows = filter
? await db
.select({ value: bookGenres.genre, count: bookCount })
.from(bookToGenres)
.innerJoin(bookGenres, eq(bookGenres.id, bookToGenres.genreId))
.innerJoin(books, eq(books.id, bookToGenres.bookId))
.where(filter)
.groupBy(bookGenres.id)
.orderBy(desc(bookCount), asc(bookGenres.genre))
: await db
.select({ value: bookGenres.genre, count: bookCount })
.from(bookGenres)
.leftJoin(bookToGenres, eq(bookToGenres.genreId, bookGenres.id))
.groupBy(bookGenres.id)
.orderBy(desc(bookCount), asc(bookGenres.genre));

return rows;
}

// Counts the books for each language or book format, skipping books without one
async function countColumn(
name: "language" | "bookFormat",
filter?: SQL,
): Promise<FacetValue[]> {
const column = books[name];
const rows = await db
.select({ value: column, count: count() })
.from(books)
.where(and(isNotNull(column), filter))
.groupBy(column)
.orderBy(desc(count()), asc(column));

return rows.flatMap((row) =>
row.value ? [{ value: row.value, count: row.count }] : [],
);
}

// The counts for all books only change with the dataset, so they are computed
// once per server process and shared between all users. Restart the server
// after reseeding.
function cacheOnce<T>(load: () => Promise<T>) {
let cached: Promise<T> | undefined;

return () => {
cached ??= load().catch((error: unknown) => {
// Let the next request try again instead of caching the failure
cached = undefined;
throw error;
});
return cached;
};
}

const allGenres = cacheOnce(() => countGenres());
const allLanguages = cacheOnce(() => countColumn("language"));
const allBookFormats = cacheOnce(() => countColumn("bookFormat"));

export { allBookFormats, allGenres, allLanguages, countColumn, countGenres };
27 changes: 27 additions & 0 deletions backend/src/schema/books/resolvers/BookFacets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { BookFacetsResolvers } from "./../../types.generated";
import { buildBookFilter } from "~/schema/books/bookFilter";
import {
allBookFormats,
allGenres,
allLanguages,
countColumn,
countGenres,
} from "~/schema/books/facets";

// Each list is counted without its own filter, so the user can still switch to
// another option. When nothing else is filtered, the cached counts for all
// books are used instead
export const BookFacets: BookFacetsResolvers = {
genres: (args) => {
const filter = buildBookFilter(args, { ignore: "genres" });
return filter ? countGenres(filter) : allGenres();
},
languages: (args) => {
const filter = buildBookFilter(args, { ignore: "language" });
return filter ? countColumn("language", filter) : allLanguages();
},
bookFormats: (args) => {
const filter = buildBookFilter(args, { ignore: "bookFormat" });
return filter ? countColumn("bookFormat", filter) : allBookFormats();
},
};
2 changes: 2 additions & 0 deletions backend/src/schema/books/resolvers/FacetValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import type { FacetValueResolvers } from "./../../types.generated";
export const FacetValue: FacetValueResolvers = {};
12 changes: 12 additions & 0 deletions backend/src/schema/books/resolvers/Query/bookFacets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { QueryResolvers } from "./../../../types.generated";
import { assertBookFilterArgs } from "~/schema/books/bookFilter";

// The lists are counted by the BookFacets field resolvers, so only the lists
// the query asks for are counted
export const bookFacets: NonNullable<QueryResolvers["bookFacets"]> = (
_parent,
args,
) => {
assertBookFilterArgs(args);
return args;
};
32 changes: 5 additions & 27 deletions backend/src/schema/books/resolvers/Query/bookFormats.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,7 @@
import { asc, count, desc, isNotNull } from "drizzle-orm";
import type { QueryResolvers } from "~/schema/types.generated";
import { db } from "~/db";
import { books } from "~/db/schema";
import { allBookFormats } from "~/schema/books/facets";

// The list only changes with the dataset, so it is computed once per server
// process and shared between all users. Restart the server after reseeding.
let cached: Promise<string[]> | undefined;

async function loadBookFormats() {
// Order by each format's book count, and then alphabetically
const rows = await db
.select({ bookFormat: books.bookFormat })
.from(books)
.where(isNotNull(books.bookFormat))
.groupBy(books.bookFormat)
.orderBy(desc(count()), asc(books.bookFormat));

return rows.flatMap((row) => (row.bookFormat ? [row.bookFormat] : []));
}

export const bookFormats: NonNullable<QueryResolvers["bookFormats"]> = () => {
cached ??= loadBookFormats().catch((error: unknown) => {
// Let the next request try again instead of caching the failure
cached = undefined;
throw error;
});
return cached;
};
// The same cached counts as bookFacets uses when nothing is filtered
export const bookFormats: NonNullable<
QueryResolvers["bookFormats"]
> = async () => (await allBookFormats()).map((option) => option.value);
31 changes: 4 additions & 27 deletions backend/src/schema/books/resolvers/Query/genres.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,6 @@
import { asc, count, desc, eq } from "drizzle-orm";
import type { QueryResolvers } from "~/schema/types.generated";
import { db } from "~/db";
import { bookGenres, bookToGenres } from "~/db/schema";
import { allGenres } from "~/schema/books/facets";

// The list only changes with the dataset, so it is computed once per server
// process and shared between all users. Restart the server after reseeding.
let cached: Promise<string[]> | undefined;

async function loadGenres() {
// Order by each genre's book count, and then alphabetically
const rows = await db
.select({ genre: bookGenres.genre })
.from(bookGenres)
.leftJoin(bookToGenres, eq(bookToGenres.genreId, bookGenres.id))
.groupBy(bookGenres.id)
.orderBy(desc(count(bookToGenres.bookId)), asc(bookGenres.genre));

return rows.map((row) => row.genre);
}

export const genres: NonNullable<QueryResolvers["genres"]> = () => {
cached ??= loadGenres().catch((error: unknown) => {
// Let the next request try again instead of caching the failure
cached = undefined;
throw error;
});
return cached;
};
// The same cached counts as bookFacets uses when nothing is filtered
export const genres: NonNullable<QueryResolvers["genres"]> = async () =>
(await allGenres()).map((option) => option.value);
31 changes: 4 additions & 27 deletions backend/src/schema/books/resolvers/Query/languages.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,6 @@
import { asc, count, desc, isNotNull } from "drizzle-orm";
import type { QueryResolvers } from "~/schema/types.generated";
import { db } from "~/db";
import { books } from "~/db/schema";
import { allLanguages } from "~/schema/books/facets";

// The list only changes with the dataset, so it is computed once per server
// process and shared between all users. Restart the server after reseeding.
let cached: Promise<string[]> | undefined;

async function loadLanguages() {
// Order by each language's book count, and then alphabetically
const rows = await db
.select({ language: books.language })
.from(books)
.where(isNotNull(books.language))
.groupBy(books.language)
.orderBy(desc(count()), asc(books.language));

return rows.flatMap((row) => (row.language ? [row.language] : []));
}

export const languages: NonNullable<QueryResolvers["languages"]> = () => {
cached ??= loadLanguages().catch((error: unknown) => {
// Let the next request try again instead of caching the failure
cached = undefined;
throw error;
});
return cached;
};
// The same cached counts as bookFacets uses when nothing is filtered
export const languages: NonNullable<QueryResolvers["languages"]> = async () =>
(await allLanguages()).map((option) => option.value);
Loading