diff --git a/backend/README.md b/backend/README.md index c683c91b..32d9a0c4 100644 --- a/backend/README.md +++ b/backend/README.md @@ -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] diff --git a/backend/src/schema/books/bookFilter.ts b/backend/src/schema/books/bookFilter.ts new file mode 100644 index 00000000..dec2ed18 --- /dev/null +++ b/backend/src/schema/books/bookFilter.ts @@ -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, +}; diff --git a/backend/src/schema/books/facets.ts b/backend/src/schema/books/facets.ts new file mode 100644 index 00000000..6de9e776 --- /dev/null +++ b/backend/src/schema/books/facets.ts @@ -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 { + 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 { + 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(load: () => Promise) { + let cached: Promise | 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 }; diff --git a/backend/src/schema/books/resolvers/BookFacets.ts b/backend/src/schema/books/resolvers/BookFacets.ts new file mode 100644 index 00000000..88e7962d --- /dev/null +++ b/backend/src/schema/books/resolvers/BookFacets.ts @@ -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(); + }, +}; diff --git a/backend/src/schema/books/resolvers/FacetValue.ts b/backend/src/schema/books/resolvers/FacetValue.ts new file mode 100644 index 00000000..36c47493 --- /dev/null +++ b/backend/src/schema/books/resolvers/FacetValue.ts @@ -0,0 +1,2 @@ +import type { FacetValueResolvers } from "./../../types.generated"; +export const FacetValue: FacetValueResolvers = {}; diff --git a/backend/src/schema/books/resolvers/Query/bookFacets.ts b/backend/src/schema/books/resolvers/Query/bookFacets.ts new file mode 100644 index 00000000..3030c28b --- /dev/null +++ b/backend/src/schema/books/resolvers/Query/bookFacets.ts @@ -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 = ( + _parent, + args, +) => { + assertBookFilterArgs(args); + return args; +}; diff --git a/backend/src/schema/books/resolvers/Query/bookFormats.ts b/backend/src/schema/books/resolvers/Query/bookFormats.ts index 17f74d6a..5f7f368a 100644 --- a/backend/src/schema/books/resolvers/Query/bookFormats.ts +++ b/backend/src/schema/books/resolvers/Query/bookFormats.ts @@ -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 | 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 = () => { - 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); diff --git a/backend/src/schema/books/resolvers/Query/genres.ts b/backend/src/schema/books/resolvers/Query/genres.ts index cfda9348..ea1d5c71 100644 --- a/backend/src/schema/books/resolvers/Query/genres.ts +++ b/backend/src/schema/books/resolvers/Query/genres.ts @@ -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 | 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 = () => { - 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 = async () => + (await allGenres()).map((option) => option.value); diff --git a/backend/src/schema/books/resolvers/Query/languages.ts b/backend/src/schema/books/resolvers/Query/languages.ts index f5bb002a..6d1e6b92 100644 --- a/backend/src/schema/books/resolvers/Query/languages.ts +++ b/backend/src/schema/books/resolvers/Query/languages.ts @@ -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 | 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 = () => { - 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 = async () => + (await allLanguages()).map((option) => option.value); diff --git a/backend/src/schema/books/resolvers/Query/searchBooks.ts b/backend/src/schema/books/resolvers/Query/searchBooks.ts index bbf06ac4..db804655 100644 --- a/backend/src/schema/books/resolvers/Query/searchBooks.ts +++ b/backend/src/schema/books/resolvers/Query/searchBooks.ts @@ -1,20 +1,11 @@ -import { - and, - asc, - desc, - eq, - exists, - gte, - ilike, - lte, - or, - sql, - type SQL, -} from "drizzle-orm"; -import { GraphQLError } from "graphql/error"; +import { asc, desc, sql, type SQL } from "drizzle-orm"; import { db } from "~/db"; import { assertLimit, assertOffset } from "~/schema/pagination"; -import { bookGenres, books, bookToGenres } from "~/db/schema"; +import { + assertBookFilterArgs, + buildBookFilter, +} from "~/schema/books/bookFilter"; +import { books } from "~/db/schema"; import type { BookSortField, QueryResolvers, @@ -78,81 +69,18 @@ const ORDER_BY: Record> = { }, }; -const MAX_GENRES = 15; -const MAX_TEXT_LENGTH = 200; - export const searchBooks: NonNullable = async ( _parent, args, ) => { assertLimit(args.limit); assertOffset(args.offset); - - 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" } }, - ); - } - - 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) conditions.push(eq(books.language, args.language)); - if (args.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)); - - const genreConditions: SQL[] = []; - - for (const genre of 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); - } + assertBookFilterArgs(args); // Here we build the filter once with Drizzle's SQL builder, so the same filter // can be used both for fetching one page and for counting all matches. - const filter = and(...conditions); + // bookFacets builds its filters the same way, see bookFilter.ts + const filter = buildBookFilter(args); const sortBy = args.sortBy; let orderBy = ORDER_BY[sortBy][args.sortDirection]; diff --git a/backend/src/schema/books/schema.graphql b/backend/src/schema/books/schema.graphql index 8a07253c..9f51c3fa 100644 --- a/backend/src/schema/books/schema.graphql +++ b/backend/src/schema/books/schema.graphql @@ -58,9 +58,42 @@ extend type Query { sortBy: BookSortField! = RELEVANCE sortDirection: SortDirection! = ASC ): BookSearchResult! + + """ + The filter options that give results for a search, with the number of books + for each option. Takes the same filters as searchBooks. + Each list ignores its own filter, so the user can still switch to another + option. For example, the languages are counted as if no language was selected. + """ + bookFacets( + query: String + fuzzy: Boolean! = false + series: String + author: String + language: String + bookFormat: String + publisher: String + genres: [String!] + minPages: Int + maxPages: Int + minRatings: Int + ): BookFacets! } type BookSearchResult { books: [Book!]! totalCount: Int! } + +"A filter option and the number of books it gives" +type FacetValue { + value: String! + count: Int! +} + +"Only options with at least one book are included, most books first" +type BookFacets { + genres: [FacetValue!]! + languages: [FacetValue!]! + bookFormats: [FacetValue!]! +} diff --git a/backend/src/schema/books/schema.mappers.ts b/backend/src/schema/books/schema.mappers.ts index 4f49314a..a2c1e3f7 100644 --- a/backend/src/schema/books/schema.mappers.ts +++ b/backend/src/schema/books/schema.mappers.ts @@ -1,7 +1,12 @@ import type { SelectBook } from "~/db/schema/books"; +import type { BookFilterArgs } from "~/schema/books/bookFilter"; // Resolvers return the DB row for a book. // The genres are resolved by the Book field resolver instead type BookMapper = SelectBook; -export { type BookMapper }; +// bookFacets returns its arguments, and each list is counted by the BookFacets +// field resolvers. That way only the lists a query asks for are counted +type BookFacetsMapper = BookFilterArgs; + +export { type BookMapper, type BookFacetsMapper }; diff --git a/backend/src/schema/resolvers.generated.ts b/backend/src/schema/resolvers.generated.ts index f0397cc5..a9add6a5 100644 --- a/backend/src/schema/resolvers.generated.ts +++ b/backend/src/schema/resolvers.generated.ts @@ -1,6 +1,7 @@ /* This file was automatically generated. DO NOT UPDATE MANUALLY. */ import type { Resolvers } from './types.generated'; import { book as Query_book } from './books/resolvers/Query/book'; +import { bookFacets as Query_bookFacets } from './books/resolvers/Query/bookFacets'; import { bookFormats as Query_bookFormats } from './books/resolvers/Query/bookFormats'; import { bookReviews as Query_bookReviews } from './reviews/resolvers/Query/bookReviews'; import { favoriteBookIds as Query_favoriteBookIds } from './favorites/resolvers/Query/favoriteBookIds'; @@ -16,16 +17,20 @@ import { deleteReview as Mutation_deleteReview } from './reviews/resolvers/Mu import { removeFavoriteBook as Mutation_removeFavoriteBook } from './favorites/resolvers/Mutation/removeFavoriteBook'; import { upsertReview as Mutation_upsertReview } from './reviews/resolvers/Mutation/upsertReview'; import { Book } from './books/resolvers/Book'; +import { BookFacets } from './books/resolvers/BookFacets'; import { BookSearchResult } from './books/resolvers/BookSearchResult'; +import { FacetValue } from './books/resolvers/FacetValue'; import { Review } from './reviews/resolvers/Review'; import { ReviewAuthor } from './reviews/resolvers/ReviewAuthor'; import { ReviewSearchResult } from './reviews/resolvers/ReviewSearchResult'; export const resolvers: Resolvers = { - Query: { book: Query_book,bookFormats: Query_bookFormats,bookReviews: Query_bookReviews,favoriteBookIds: Query_favoriteBookIds,favoriteBooks: Query_favoriteBooks,favoriteGenres: Query_favoriteGenres,genres: Query_genres,languages: Query_languages,myReview: Query_myReview,myReviews: Query_myReviews,searchBooks: Query_searchBooks }, + Query: { book: Query_book,bookFacets: Query_bookFacets,bookFormats: Query_bookFormats,bookReviews: Query_bookReviews,favoriteBookIds: Query_favoriteBookIds,favoriteBooks: Query_favoriteBooks,favoriteGenres: Query_favoriteGenres,genres: Query_genres,languages: Query_languages,myReview: Query_myReview,myReviews: Query_myReviews,searchBooks: Query_searchBooks }, Mutation: { addFavoriteBook: Mutation_addFavoriteBook,deleteReview: Mutation_deleteReview,removeFavoriteBook: Mutation_removeFavoriteBook,upsertReview: Mutation_upsertReview }, Book: Book, +BookFacets: BookFacets, BookSearchResult: BookSearchResult, +FacetValue: FacetValue, Review: Review, ReviewAuthor: ReviewAuthor, ReviewSearchResult: ReviewSearchResult diff --git a/backend/src/schema/schema.generated.graphqls b/backend/src/schema/schema.generated.graphqls index 49cb6cf5..98d68382 100644 --- a/backend/src/schema/schema.generated.graphqls +++ b/backend/src/schema/schema.generated.graphqls @@ -18,6 +18,13 @@ type Book { title: String! } +"""Only options with at least one book are included, most books first""" +type BookFacets { + bookFormats: [FacetValue!]! + genres: [FacetValue!]! + languages: [FacetValue!]! +} + type BookSearchResult { books: [Book!]! totalCount: Int! @@ -33,6 +40,12 @@ enum BookSortField { TITLE } +"""A filter option and the number of books it gives""" +type FacetValue { + count: Int! + value: String! +} + type Mutation { addFavoriteBook(bookId: Int!): Book! @@ -50,6 +63,14 @@ type Mutation { type Query { book(id: Int!): Book + + """ + The filter options that give results for a search, with the number of books + for each option. Takes the same filters as searchBooks. + Each list ignores its own filter, so the user can still switch to another + option. For example, the languages are counted as if no language was selected. + """ + bookFacets(author: String, bookFormat: String, fuzzy: Boolean! = false, genres: [String!], language: String, maxPages: Int, minPages: Int, minRatings: Int, publisher: String, query: String, series: String): BookFacets! bookFormats: [String!]! """Reviews of a book, newest first.""" diff --git a/backend/src/schema/typeDefs.generated.ts b/backend/src/schema/typeDefs.generated.ts index 0953c849..b136a976 100644 --- a/backend/src/schema/typeDefs.generated.ts +++ b/backend/src/schema/typeDefs.generated.ts @@ -1,2 +1,2 @@ import type { DocumentNode } from 'graphql'; - export const typeDefs = {"kind":"Document","definitions":[{"name":{"kind":"Name","value":"Query"},"kind":"ObjectTypeDefinition","fields":[{"kind":"FieldDefinition","name":{"kind":"Name","value":"book"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"id"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"type":{"kind":"NamedType","name":{"kind":"Name","value":"Book"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"genres"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"languages"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"bookFormats"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"searchBooks"},"arguments":[{"kind":"InputValueDefinition","description":{"kind":"StringValue","value":"Match books where either the title or the author contains the query","block":false},"name":{"kind":"Name","value":"query"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","description":{"kind":"StringValue","value":"Match titles and authors that are similar to the query, for example with typos, ordered by similarity","block":false},"name":{"kind":"Name","value":"fuzzy"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}},"defaultValue":{"kind":"BooleanValue","value":false}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"series"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"author"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"language"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"bookFormat"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"publisher"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"genres"},"type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"minPages"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"maxPages"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"minRatings"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"limit"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"12"}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"offset"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"0"}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"sortBy"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"BookSortField"}}},"defaultValue":{"kind":"EnumValue","value":"RELEVANCE"}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"sortDirection"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SortDirection"}}},"defaultValue":{"kind":"EnumValue","value":"ASC"}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"BookSearchResult"}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"Favorite books of the logged-in user, newest first.","block":false},"name":{"kind":"Name","value":"favoriteBooks"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"limit"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"12"}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"offset"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"0"}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"BookSearchResult"}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"ID of every book the logged-in user that has been added to their favorites.","block":false},"name":{"kind":"Name","value":"favoriteBookIds"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"The logged-in user's most common genres among their favorite books.","block":false},"name":{"kind":"Name","value":"favoriteGenres"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"limit"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"3"}}],"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"Reviews of a book, newest first.","block":false},"name":{"kind":"Name","value":"bookReviews"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"bookId"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"limit"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"10"}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"offset"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"0"}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ReviewSearchResult"}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"The logged-in user's review of a book, or null if they have not reviewed it.","block":false},"name":{"kind":"Name","value":"myReview"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"bookId"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"type":{"kind":"NamedType","name":{"kind":"Name","value":"Review"}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"Reviews written by the logged-in user, newest first.","block":false},"name":{"kind":"Name","value":"myReviews"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"limit"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"10"}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"offset"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"0"}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ReviewSearchResult"}}}}],"directives":[],"interfaces":[]},{"name":{"kind":"Name","value":"Mutation"},"kind":"ObjectTypeDefinition","fields":[{"kind":"FieldDefinition","name":{"kind":"Name","value":"addFavoriteBook"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"bookId"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Book"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"removeFavoriteBook"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"bookId"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"Create the logged-in user's review of a book, or update it if it already exists.","block":false},"name":{"kind":"Name","value":"upsertReview"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"bookId"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"rating"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"comment"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Review"}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"Delete the logged-in user's review of a book. Returns the book with its updated rating.","block":false},"name":{"kind":"Name","value":"deleteReview"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"bookId"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Book"}}}}],"directives":[],"interfaces":[]},{"kind":"ObjectTypeDefinition","name":{"kind":"Name","value":"Book"},"fields":[{"kind":"FieldDefinition","name":{"kind":"Name","value":"id"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"isbn"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"title"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"series"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"author"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"description"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"language"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"bookFormat"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"edition"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"pages"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"publisher"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"publishDate"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"publishYear"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"coverImgUrl"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"genres"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"rating"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Float"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"numRatings"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}]},{"kind":"EnumTypeDefinition","name":{"kind":"Name","value":"BookSortField"},"values":[{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"RELEVANCE"}},{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"ID"}},{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"RATING"}},{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"TITLE"}},{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"NUM_RATINGS"}},{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"PAGES"}},{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"PUBLISH_YEAR"}}]},{"kind":"EnumTypeDefinition","name":{"kind":"Name","value":"SortDirection"},"values":[{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"ASC"}},{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"DESC"}}]},{"kind":"ObjectTypeDefinition","name":{"kind":"Name","value":"BookSearchResult"},"fields":[{"kind":"FieldDefinition","name":{"kind":"Name","value":"books"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Book"}}}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"totalCount"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}]},{"kind":"ObjectTypeDefinition","name":{"kind":"Name","value":"Review"},"fields":[{"kind":"FieldDefinition","name":{"kind":"Name","value":"id"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"rating"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"comment"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"ISO 8601 timestamp","block":false},"name":{"kind":"Name","value":"createdAt"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"ISO 8601 timestamp","block":false},"name":{"kind":"Name","value":"updatedAt"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"user"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ReviewAuthor"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"book"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Book"}}}}]},{"kind":"ObjectTypeDefinition","name":{"kind":"Name","value":"ReviewAuthor"},"fields":[{"kind":"FieldDefinition","name":{"kind":"Name","value":"id"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"name"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"image"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}]},{"kind":"ObjectTypeDefinition","name":{"kind":"Name","value":"ReviewSearchResult"},"fields":[{"kind":"FieldDefinition","name":{"kind":"Name","value":"reviews"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Review"}}}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"totalCount"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}]},{"kind":"SchemaDefinition","operationTypes":[{"kind":"OperationTypeDefinition","type":{"kind":"NamedType","name":{"kind":"Name","value":"Query"}},"operation":"query"},{"kind":"OperationTypeDefinition","type":{"kind":"NamedType","name":{"kind":"Name","value":"Mutation"}},"operation":"mutation"}]}]} as unknown as DocumentNode \ No newline at end of file + export const typeDefs = {"kind":"Document","definitions":[{"name":{"kind":"Name","value":"Query"},"kind":"ObjectTypeDefinition","fields":[{"kind":"FieldDefinition","name":{"kind":"Name","value":"book"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"id"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"type":{"kind":"NamedType","name":{"kind":"Name","value":"Book"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"genres"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"languages"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"bookFormats"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"searchBooks"},"arguments":[{"kind":"InputValueDefinition","description":{"kind":"StringValue","value":"Match books where either the title or the author contains the query","block":false},"name":{"kind":"Name","value":"query"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","description":{"kind":"StringValue","value":"Match titles and authors that are similar to the query, for example with typos, ordered by similarity","block":false},"name":{"kind":"Name","value":"fuzzy"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}},"defaultValue":{"kind":"BooleanValue","value":false}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"series"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"author"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"language"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"bookFormat"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"publisher"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"genres"},"type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"minPages"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"maxPages"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"minRatings"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"limit"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"12"}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"offset"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"0"}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"sortBy"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"BookSortField"}}},"defaultValue":{"kind":"EnumValue","value":"RELEVANCE"}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"sortDirection"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SortDirection"}}},"defaultValue":{"kind":"EnumValue","value":"ASC"}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"BookSearchResult"}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"The filter options that give results for a search, with the number of books\nfor each option. Takes the same filters as searchBooks.\nEach list ignores its own filter, so the user can still switch to another\noption. For example, the languages are counted as if no language was selected.","block":true},"name":{"kind":"Name","value":"bookFacets"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"query"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"fuzzy"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}},"defaultValue":{"kind":"BooleanValue","value":false}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"series"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"author"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"language"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"bookFormat"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"publisher"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"genres"},"type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"minPages"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"maxPages"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"minRatings"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"BookFacets"}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"Favorite books of the logged-in user, newest first.","block":false},"name":{"kind":"Name","value":"favoriteBooks"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"limit"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"12"}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"offset"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"0"}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"BookSearchResult"}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"ID of every book the logged-in user that has been added to their favorites.","block":false},"name":{"kind":"Name","value":"favoriteBookIds"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"The logged-in user's most common genres among their favorite books.","block":false},"name":{"kind":"Name","value":"favoriteGenres"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"limit"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"3"}}],"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"Reviews of a book, newest first.","block":false},"name":{"kind":"Name","value":"bookReviews"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"bookId"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"limit"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"10"}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"offset"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"0"}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ReviewSearchResult"}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"The logged-in user's review of a book, or null if they have not reviewed it.","block":false},"name":{"kind":"Name","value":"myReview"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"bookId"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"type":{"kind":"NamedType","name":{"kind":"Name","value":"Review"}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"Reviews written by the logged-in user, newest first.","block":false},"name":{"kind":"Name","value":"myReviews"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"limit"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"10"}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"offset"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},"defaultValue":{"kind":"IntValue","value":"0"}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ReviewSearchResult"}}}}],"directives":[],"interfaces":[]},{"name":{"kind":"Name","value":"Mutation"},"kind":"ObjectTypeDefinition","fields":[{"kind":"FieldDefinition","name":{"kind":"Name","value":"addFavoriteBook"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"bookId"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Book"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"removeFavoriteBook"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"bookId"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"Create the logged-in user's review of a book, or update it if it already exists.","block":false},"name":{"kind":"Name","value":"upsertReview"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"bookId"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"rating"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"InputValueDefinition","name":{"kind":"Name","value":"comment"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Review"}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"Delete the logged-in user's review of a book. Returns the book with its updated rating.","block":false},"name":{"kind":"Name","value":"deleteReview"},"arguments":[{"kind":"InputValueDefinition","name":{"kind":"Name","value":"bookId"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Book"}}}}],"directives":[],"interfaces":[]},{"kind":"ObjectTypeDefinition","name":{"kind":"Name","value":"Book"},"fields":[{"kind":"FieldDefinition","name":{"kind":"Name","value":"id"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"isbn"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"title"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"series"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"author"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"description"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"language"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"bookFormat"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"edition"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"pages"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"publisher"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"publishDate"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"publishYear"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"coverImgUrl"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"genres"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"rating"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Float"}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"numRatings"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}]},{"kind":"EnumTypeDefinition","name":{"kind":"Name","value":"BookSortField"},"values":[{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"RELEVANCE"}},{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"ID"}},{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"RATING"}},{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"TITLE"}},{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"NUM_RATINGS"}},{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"PAGES"}},{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"PUBLISH_YEAR"}}]},{"kind":"EnumTypeDefinition","name":{"kind":"Name","value":"SortDirection"},"values":[{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"ASC"}},{"kind":"EnumValueDefinition","name":{"kind":"Name","value":"DESC"}}]},{"kind":"ObjectTypeDefinition","name":{"kind":"Name","value":"BookSearchResult"},"fields":[{"kind":"FieldDefinition","name":{"kind":"Name","value":"books"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Book"}}}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"totalCount"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}]},{"kind":"ObjectTypeDefinition","description":{"kind":"StringValue","value":"A filter option and the number of books it gives","block":false},"name":{"kind":"Name","value":"FacetValue"},"fields":[{"kind":"FieldDefinition","name":{"kind":"Name","value":"value"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"count"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}]},{"kind":"ObjectTypeDefinition","description":{"kind":"StringValue","value":"Only options with at least one book are included, most books first","block":false},"name":{"kind":"Name","value":"BookFacets"},"fields":[{"kind":"FieldDefinition","name":{"kind":"Name","value":"genres"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"FacetValue"}}}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"languages"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"FacetValue"}}}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"bookFormats"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"FacetValue"}}}}}}]},{"kind":"ObjectTypeDefinition","name":{"kind":"Name","value":"Review"},"fields":[{"kind":"FieldDefinition","name":{"kind":"Name","value":"id"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"rating"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"comment"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"ISO 8601 timestamp","block":false},"name":{"kind":"Name","value":"createdAt"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"FieldDefinition","description":{"kind":"StringValue","value":"ISO 8601 timestamp","block":false},"name":{"kind":"Name","value":"updatedAt"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"user"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ReviewAuthor"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"book"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Book"}}}}]},{"kind":"ObjectTypeDefinition","name":{"kind":"Name","value":"ReviewAuthor"},"fields":[{"kind":"FieldDefinition","name":{"kind":"Name","value":"id"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"name"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"image"},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}]},{"kind":"ObjectTypeDefinition","name":{"kind":"Name","value":"ReviewSearchResult"},"fields":[{"kind":"FieldDefinition","name":{"kind":"Name","value":"reviews"},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Review"}}}}}},{"kind":"FieldDefinition","name":{"kind":"Name","value":"totalCount"},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}]},{"kind":"SchemaDefinition","operationTypes":[{"kind":"OperationTypeDefinition","type":{"kind":"NamedType","name":{"kind":"Name","value":"Query"}},"operation":"query"},{"kind":"OperationTypeDefinition","type":{"kind":"NamedType","name":{"kind":"Name","value":"Mutation"}},"operation":"mutation"}]}]} as unknown as DocumentNode \ No newline at end of file diff --git a/backend/src/schema/types.generated.ts b/backend/src/schema/types.generated.ts index 26cdc3c9..1af5d20f 100644 --- a/backend/src/schema/types.generated.ts +++ b/backend/src/schema/types.generated.ts @@ -1,5 +1,5 @@ import type { GraphQLResolveInfo } from 'graphql'; -import type { BookMapper } from './books/schema.mappers'; +import type { BookMapper, BookFacetsMapper } from './books/schema.mappers'; import type { ReviewMapper } from './reviews/schema.mappers'; import type { ApolloContext } from '~/index'; export type Maybe = T | null | undefined; @@ -37,6 +37,14 @@ export type Book = { title: Scalars['String']['output']; }; +/** Only options with at least one book are included, most books first */ +export type BookFacets = { + __typename?: 'BookFacets'; + bookFormats: Array; + genres: Array; + languages: Array; +}; + export type BookSearchResult = { __typename?: 'BookSearchResult'; books: Array; @@ -52,6 +60,13 @@ export type BookSortField = | 'RELEVANCE' | 'TITLE'; +/** A filter option and the number of books it gives */ +export type FacetValue = { + __typename?: 'FacetValue'; + count: Scalars['Int']['output']; + value: Scalars['String']['output']; +}; + export type Mutation = { __typename?: 'Mutation'; addFavoriteBook: Book; @@ -87,6 +102,13 @@ export type MutationupsertReviewArgs = { export type Query = { __typename?: 'Query'; book?: Maybe; + /** + * The filter options that give results for a search, with the number of books + * for each option. Takes the same filters as searchBooks. + * Each list ignores its own filter, so the user can still switch to another + * option. For example, the languages are counted as if no language was selected. + */ + bookFacets: BookFacets; bookFormats: Array; /** Reviews of a book, newest first. */ bookReviews: ReviewSearchResult; @@ -111,6 +133,21 @@ export type QuerybookArgs = { }; +export type QuerybookFacetsArgs = { + author?: InputMaybe; + bookFormat?: InputMaybe; + fuzzy?: Scalars['Boolean']['input']; + genres?: InputMaybe>; + language?: InputMaybe; + maxPages?: InputMaybe; + minPages?: InputMaybe; + minRatings?: InputMaybe; + publisher?: InputMaybe; + query?: InputMaybe; + series?: InputMaybe; +}; + + export type QuerybookReviewsArgs = { bookId: Scalars['Int']['input']; limit?: Scalars['Int']['input']; @@ -265,8 +302,10 @@ export type ResolversTypes = { String: ResolverTypeWrapper; Int: ResolverTypeWrapper; Float: ResolverTypeWrapper; + BookFacets: ResolverTypeWrapper; BookSearchResult: ResolverTypeWrapper & { books: Array }>; BookSortField: ResolverTypeWrapper<'RELEVANCE' | 'ID' | 'RATING' | 'TITLE' | 'NUM_RATINGS' | 'PAGES' | 'PUBLISH_YEAR'>; + FacetValue: ResolverTypeWrapper; Mutation: ResolverTypeWrapper>; Boolean: ResolverTypeWrapper; Query: ResolverTypeWrapper>; @@ -282,7 +321,9 @@ export type ResolversParentTypes = { String: Scalars['String']['output']; Int: Scalars['Int']['output']; Float: Scalars['Float']['output']; + BookFacets: BookFacetsMapper; BookSearchResult: Omit & { books: Array }; + FacetValue: FacetValue; Mutation: Record; Boolean: Scalars['Boolean']['output']; Query: Record; @@ -311,6 +352,12 @@ export type BookResolvers; }; +export type BookFacetsResolvers = { + bookFormats?: Resolver, ParentType, ContextType>; + genres?: Resolver, ParentType, ContextType>; + languages?: Resolver, ParentType, ContextType>; +}; + export type BookSearchResultResolvers = { books?: Resolver, ParentType, ContextType>; totalCount?: Resolver; @@ -318,6 +365,11 @@ export type BookSearchResultResolvers; +export type FacetValueResolvers = { + count?: Resolver; + value?: Resolver; +}; + export type MutationResolvers = { addFavoriteBook?: Resolver>; deleteReview?: Resolver>; @@ -327,6 +379,7 @@ export type MutationResolvers = { book?: Resolver, ParentType, ContextType, RequireFields>; + bookFacets?: Resolver>; bookFormats?: Resolver, ParentType, ContextType>; bookReviews?: Resolver>; favoriteBookIds?: Resolver, ParentType, ContextType>; @@ -364,8 +417,10 @@ export type SortDirectionResolvers = EnumResolverSignature<{ ASC?: any, DESC?: a export type Resolvers = { Book?: BookResolvers; + BookFacets?: BookFacetsResolvers; BookSearchResult?: BookSearchResultResolvers; BookSortField?: BookSortFieldResolvers; + FacetValue?: FacetValueResolvers; Mutation?: MutationResolvers; Query?: QueryResolvers; Review?: ReviewResolvers; diff --git a/backend/tests/books.test.ts b/backend/tests/books.test.ts index 49593e9f..49b09e05 100644 --- a/backend/tests/books.test.ts +++ b/backend/tests/books.test.ts @@ -224,3 +224,143 @@ describe("filter options", () => { }); }); }); + +describe("bookFacets", () => { + const BOOK_FACETS = ` + query BookFacets( + $query: String + $genres: [String!] + $language: String + $bookFormat: String + $maxPages: Int + ) { + bookFacets( + query: $query + genres: $genres + language: $language + bookFormat: $bookFormat + maxPages: $maxPages + ) { + genres { value count } + languages { value count } + bookFormats { value count } + } + } + `; + + interface FacetValue { + value: string; + count: number; + } + + interface BookFacetsData { + bookFacets: { + genres: FacetValue[]; + languages: FacetValue[]; + bookFormats: FacetValue[]; + }; + } + + async function bookFacets(variables: Record = {}) { + const result = await execute(BOOK_FACETS, variables); + expect(result.errors).toBeUndefined(); + assert(result.data); + return result.data.bookFacets; + } + + it("counts every book when nothing is filtered", async () => { + expect(await bookFacets()).toEqual({ + genres: [ + { value: "Fantasy", count: 4 }, + { value: "Classics", count: 3 }, + { value: "Romance", count: 1 }, + { value: "Science Fiction", count: 1 }, + ], + languages: [ + { value: "English", count: 6 }, + { value: "French", count: 1 }, + ], + bookFormats: [ + { value: "Paperback", count: 4 }, + { value: "Hardcover", count: 3 }, + ], + }); + }); + + it("only lists the options of the books matching the query", async () => { + expect(await bookFacets({ query: "abercrombie" })).toEqual({ + genres: [{ value: "Fantasy", count: 2 }], + languages: [{ value: "English", count: 2 }], + bookFormats: [ + { value: "Hardcover", count: 1 }, + { value: "Paperback", count: 1 }, + ], + }); + }); + + it("counts each list without its own filter", async () => { + // Classics: The Hobbit, Pride and Prejudice and Le Petit Prince + const facets = await bookFacets({ genres: ["Classics"] }); + + // The genres are counted as if no genre was selected + expect(facets.genres).toEqual([ + { value: "Fantasy", count: 4 }, + { value: "Classics", count: 3 }, + { value: "Romance", count: 1 }, + { value: "Science Fiction", count: 1 }, + ]); + expect(facets.languages).toEqual([ + { value: "English", count: 2 }, + { value: "French", count: 1 }, + ]); + expect(facets.bookFormats).toEqual([ + { value: "Paperback", count: 2 }, + { value: "Hardcover", count: 1 }, + ]); + + // The languages can still be switched after one is selected + expect((await bookFacets({ language: "French" })).languages).toEqual([ + { value: "English", count: 6 }, + { value: "French", count: 1 }, + ]); + }); + + it("combines the query with the other filters", async () => { + // Le Petit Prince matches "le", but has more than 90 pages + expect( + await bookFacets({ query: "le", language: "French", maxPages: 90 }), + ).toEqual({ + genres: [], + languages: [], + bookFormats: [], + }); + + // "the" matches The Blade Itself (Paperback), Before They Are Hanged + // (Hardcover) and The Hobbit (Paperback) + expect(await bookFacets({ query: "the", bookFormat: "Hardcover" })).toEqual( + { + genres: [{ value: "Fantasy", count: 1 }], + languages: [{ value: "English", count: 1 }], + bookFormats: [ + { value: "Paperback", count: 2 }, + { value: "Hardcover", count: 1 }, + ], + }, + ); + }); + + it("returns empty lists when nothing matches", async () => { + expect(await bookFacets({ query: "no such book" })).toEqual({ + genres: [], + languages: [], + bookFormats: [], + }); + }); + + it("rejects too many genres, like searchBooks", async () => { + const genres = Array.from({ length: 16 }, (_, i) => `Genre ${i}`); + const result = await execute(BOOK_FACETS, { genres }); + + expect(result.errors?.[0]?.extensions?.code).toBe("BAD_USER_INPUT"); + }); +}); diff --git a/docs/choices-and-reasoning.md b/docs/choices-and-reasoning.md index 53403ee4..217b079e 100644 --- a/docs/choices-and-reasoning.md +++ b/docs/choices-and-reasoning.md @@ -92,6 +92,20 @@ The filters were first placed in a popover, with several of the filters being dr The filters are now always visible in a panel on the left side of the books on desktop, so there is no menu to open and no dropdown on top of another menu. On smaller screens, the same filters are shown in a sheet that slides in from the side. We chose a sheet over a drawer because it is a more natural fit for a menu coming in from the side, and because swipe-to-close is not needed and could close the menu by accident while the user is still choosing filters. +## Only relevant filter options + +The genre, language and book format filters only show the options that give books for the current search and the other filters, with the number of books for each option (#158). This was suggested by our lecturer, and is what most web shops do: after searching for "tolkien", there is no point in choosing between 982 genres and 81 languages. + +The options are counted in the database by the `bookFacets` query. It takes the same filters as `searchBooks`, and both build their SQL condition with the same function (`backend/src/schema/books/bookFilter.ts`), so the counts always agree with the search results. Some choices we made: + +- **Each list ignores its own filter.** The languages are counted as if no language was chosen, so the user can still switch from French to English. Otherwise, the language list would contain French only, since all results would be in French. The same goes for genres, which are combined with OR (see above), so choosing a genre doesn't hide the others. +- **A separate query instead of a field on `searchBooks`.** The options don't depend on the page or the sort order, so Apollo Client's cache reuses them while the user browses pages or changes the sorting. Each list is counted by its own field resolver, so a query only pays for the lists it asks for. +- **Chosen options are always shown**, with 0 books if the search has none, so they can still be removed. A filter without any options is hidden, unless it is in use. +- **The page range and minimum number of ratings are unchanged**, since they are ranges and not lists of values. +- **The counts are read by screen readers** after the option's name ("Fantasy, 128 books"), using `aria-describedby`. The name of the option stays "Fantasy", so it is easy to find with a screen reader and in tests. + +Without a search or filters, the counts for all books are computed once and cached, like the lists on the home page. We measured `bookFacets` on the whole dataset (52,478 books): narrow searches take a few milliseconds, and the broadest search we tried (the letter "a", which matches almost every book) about 55 ms, in the same range as `searchBooks` itself. We therefore didn't add any more caching. + ## Playwright E2E testing We use [Playwright](https://playwright.dev/) to run end-to-end (E2E) tests. diff --git a/docs/sustainability.md b/docs/sustainability.md index 3eb2ec08..fe8b8448 100644 --- a/docs/sustainability.md +++ b/docs/sustainability.md @@ -6,7 +6,7 @@ - **Fewer requests when searching.** When searching, we have a 500 ms debounce (`SEARCH_DEBOUNCE_MS`), which waits until the user has stopped typing for 500 ms before actually sending the request. - **Small responses from GraphQL.** The book cards only fetch what is actually being displayed: `id`, `title`, `author`, `publishDate`, `coverImgUrl` and `rating`, and not the description and other heavy fields. - **No unnecessary queries.** Queries are skipped when their result is not needed (with Apollo's `skip` option and `skipToken`), for example the favorites of a user who is not logged in. -- **Cache.** Apollo uses the cache before the network for the filter lists, so genres, languages and formats are only fetched once per page load. We chose this because the lists only change when the dataset changes. +- **Cache.** Apollo uses the cache before the network. The lists of genres and languages on the home page are only fetched once per page load, since they only change when the dataset changes. The filter options on the books page depend on the search (see [Only relevant filter options](./choices-and-reasoning.md#only-relevant-filter-options)), so they are fetched again when the search or filters change. They are not fetched again when the user changes page or sorting, and a search that has been made before is read from the cache. Without a search or filters, the backend uses the counts it has already computed for all books. - **Covers are not stored on the server.** As mentioned in the [specification documentation](/docs/specifications.md), we only store the URL of each cover image. This was mainly done because of the limited storage on the VM, but it also means we don't keep a second copy of tens of thousands of images that are already hosted on Goodreads' image servers. The downside is that we can't control the size of the images, see [Limitations/Future work](#limitationsfuture-work). ## Limitations/Future work diff --git a/frontend/README.md b/frontend/README.md index 52c94d34..d7a1735a 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -114,7 +114,7 @@ intended change without catching real bugs. The tests never send real requests. We mock two things: -- **The GraphQL API.** Components that use the API are rendered inside Apollo's `MockedProvider` (through `renderRoutes`), with a list of mocked responses. A request only gets a response if both its query and its variables match a mock, so the tests also check that the components ask the API for the right data. +- **The GraphQL API.** Components that use the API are rendered inside Apollo's `MockedProvider` (through `renderRoutes`), with a list of mocked responses. A request only gets a response if both its query and its variables match a mock, so the tests also check that the components ask the API for the right data. The one exception is `bookFacetsMock` (the filter options on the books page), which answers any variables unless the test passes them, since most tests on that page are not about which options are shown. - **The session.** The tests mock `~/api/auth` with `vi.mock`, so `authClient.useSession()` returns the logged-in or logged-out user from `app/test/session.ts`, and no requests are sent to the auth server. The API itself is tested in the backend, see the [backend README](../backend/README.md#testing-the-api). diff --git a/frontend/app/api/types/graphql.generated.ts b/frontend/app/api/types/graphql.generated.ts index d29b5fd7..05ade4a6 100644 --- a/frontend/app/api/types/graphql.generated.ts +++ b/frontend/app/api/types/graphql.generated.ts @@ -22,10 +22,23 @@ export type BookQueryVariables = Exact<{ export type BookQuery = { book: { __typename: 'Book', id: number, isbn: string, title: string, author: string, language: string | null, publishYear: number | null, coverImgUrl: string | null, description: string | null, rating: number | null, numRatings: number | null } | null }; +export type BookFacetsQueryVariables = Exact<{ + query?: string | null | undefined; + genres?: Array | string | null | undefined; + language?: string | null | undefined; + bookFormat?: string | null | undefined; + minPages?: number | null | undefined; + maxPages?: number | null | undefined; + minRatings?: number | null | undefined; +}>; + + +export type BookFacetsQuery = { bookFacets: { __typename: 'BookFacets', genres: Array<{ __typename: 'FacetValue', value: string, count: number }>, languages: Array<{ __typename: 'FacetValue', value: string, count: number }>, bookFormats: Array<{ __typename: 'FacetValue', value: string, count: number }> } }; + export type BookFiltersQueryVariables = Exact<{ [key: string]: never; }>; -export type BookFiltersQuery = { genres: Array, languages: Array, bookFormats: Array }; +export type BookFiltersQuery = { genres: Array, languages: Array }; export type FavoriteBooksQueryVariables = Exact<{ limit: number; diff --git a/frontend/app/api/types/index.ts b/frontend/app/api/types/index.ts index 81f8add7..5680e746 100644 --- a/frontend/app/api/types/index.ts +++ b/frontend/app/api/types/index.ts @@ -6,4 +6,11 @@ interface BookFilters { minRatings?: number; } -export { type BookFilters }; +// An option in the genre, language or book format filter, and the number of +// books it gives for the current search +interface FilterOption { + value: string; + count: number; +} + +export { type BookFilters, type FilterOption }; diff --git a/frontend/app/components/books/BookFilters/BookFilters.test.tsx b/frontend/app/components/books/BookFilters/BookFilters.test.tsx index 3ecbdfe6..24a0b9ab 100644 --- a/frontend/app/components/books/BookFilters/BookFilters.test.tsx +++ b/frontend/app/components/books/BookFilters/BookFilters.test.tsx @@ -1,18 +1,28 @@ -import { describe, expect, it, vi } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { render, screen, waitFor } from "@testing-library/react"; import userEvent, { type UserEvent } from "@testing-library/user-event"; import { createRoutesStub, Link, useSearchParams } from "react-router"; import { BookFilters } from "~/components/books/BookFilters/BookFilters"; -vi.mock("~/hooks/useBookFilters", () => ({ - useBookFilters: () => ({ - genres: ["Fantasy", "Romance", "Science Fiction"], - languages: ["English", "French", "Spanish"], - bookFormats: ["Paperback", "Hardcover"], - loading: false, - error: undefined, - }), -})); +// Turns names into options with 10, 9, 8... books, most books first +const toOptions = (values: string[]) => + values.map((value, index) => ({ value, count: 10 - index })); + +const defaultFacets = { + genres: toOptions(["Fantasy", "Romance", "Science Fiction"]), + languages: toOptions(["English", "French", "Spanish"]), + bookFormats: toOptions(["Paperback", "Hardcover"]), + loaded: true, + loading: false, + error: undefined, +}; + +const useBookFacets = vi.hoisted(() => vi.fn()); +vi.mock("~/hooks/useBookFacets", () => ({ useBookFacets })); + +beforeEach(() => { + useBookFacets.mockReturnValue(defaultFacets); +}); // Shows the current filter params so tests can assert what was written to the URL. function SearchParamProbe() { @@ -83,6 +93,59 @@ describe("FilterBooksSection", () => { ); }); + it("asks for the options of the current search and filters", () => { + render( + , + ); + + expect(useBookFacets).toHaveBeenLastCalledWith({ + query: "dune", + // The other filters are undefined, which the comparison ignores + filters: { language: "French", minRatings: 100 }, + }); + }); + + it("hides a filter that has no options for the search", () => { + useBookFacets.mockReturnValue({ ...defaultFacets, bookFormats: [] }); + render(); + + expect(screen.getByRole("button", { name: "Genres" })).toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "Book format" }), + ).not.toBeInTheDocument(); + }); + + it("keeps a filter without options when it is in use", () => { + useBookFacets.mockReturnValue({ ...defaultFacets, languages: [] }); + render(); + + // The selected language is shown with 0 books, so it can be changed + expect(screen.getByRole("radio", { name: "French" })).toBeChecked(); + expect( + screen.getByRole("radio", { name: "French" }), + ).toHaveAccessibleDescription("0 books"); + }); + + it("hides no filters before the first options have loaded", () => { + useBookFacets.mockReturnValue({ + ...defaultFacets, + genres: [], + languages: [], + bookFormats: [], + loaded: false, + loading: true, + }); + render(); + + expect(screen.getByRole("button", { name: "Genres" })).toBeInTheDocument(); + expect( + screen.getByRole("button", { name: "Language" }), + ).toBeInTheDocument(); + expect( + screen.getByRole("button", { name: "Book format" }), + ).toBeInTheDocument(); + }); + it("sets the minimum number of ratings in the URL", async () => { const user = userEvent.setup(); render(); diff --git a/frontend/app/components/books/BookFilters/BookFilters.tsx b/frontend/app/components/books/BookFilters/BookFilters.tsx index 22e86a48..760c2619 100644 --- a/frontend/app/components/books/BookFilters/BookFilters.tsx +++ b/frontend/app/components/books/BookFilters/BookFilters.tsx @@ -7,8 +7,9 @@ import { } from "~/components/ui/Accordion"; import { Badge } from "~/components/ui/Badge"; import { useSearchParams } from "react-router"; +import type { FilterOption } from "~/api/types"; import { FILTER_KEYS, useBookSearchParams } from "~/hooks/useBookSearchParams"; -import { useBookFilters } from "~/hooks/useBookFilters"; +import { useBookFacets } from "~/hooks/useBookFacets"; import { MinRatingsFilter } from "~/components/books/MinRatingsFilter/MinRatingsFilter"; import { PagesFilter } from "~/components/books/PagesFilter/PagesFilter"; import { GenreFilter } from "~/components/books/GenreFilter/GenreFilter"; @@ -53,8 +54,10 @@ function FilterSection({ function BookFilters() { const [, setSearchParams] = useSearchParams(); - const { filters, activeFiltersCount } = useBookSearchParams(); - const { languages, bookFormats } = useBookFilters(); + const { query, filters, activeFiltersCount } = useBookSearchParams(); + + // Only the options that give results for the current search are shown + const facets = useBookFacets({ query, filters }); // The filters can be rendered twice (sidebar on desktop, sheet on mobile), // so we need a unique id @@ -62,6 +65,13 @@ function BookFilters() { const genresCount = filters.genres?.length ?? 0; + // A filter without any options for the search is hidden, unless it is in + // use, so it can still be cleared. Nothing is hidden before the first + // options arrive + function hasOptions(options: FilterOption[], activeCount: number) { + return !facets.loaded || options.length > 0 || activeCount > 0; + } + // Genres start open, and so do the other filters that are in use const initSections = [ "genres", @@ -101,33 +111,43 @@ function BookFilters() { - - - - - - - - - + {hasOptions(facets.genres, genresCount) && ( + + + + )} + {hasOptions(facets.languages, filters.language ? 1 : 0) && ( + + + + )} + {hasOptions(facets.bookFormats, filters.bookFormat ? 1 : 0) && ( + + + + )} holds the count as a machine-readable value next to the formatted + // text. Screen readers get the whole text in one element, so it is read as + // "1,234 books" and not "1,234books" + return ( + + {/* The span elements provide separate visual and screen-reader text for the count. */} + + + {`${formatted} ${count === 1 ? "book" : "books"}`} + + + ); +} + +export { FilterOptionCount }; diff --git a/frontend/app/components/books/GenreFilter/GenreFilter.test.tsx b/frontend/app/components/books/GenreFilter/GenreFilter.test.tsx index e73967e7..e827c176 100644 --- a/frontend/app/components/books/GenreFilter/GenreFilter.test.tsx +++ b/frontend/app/components/books/GenreFilter/GenreFilter.test.tsx @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest"; import { render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { createRoutesStub, useSearchParams } from "react-router"; +import type { FilterOption } from "~/api/types"; import { GenreFilter } from "~/components/books/GenreFilter/GenreFilter"; import { toast } from "~/components/ui/Toast"; import { MAX_GENRES } from "~/lib/constants"; @@ -20,8 +21,10 @@ const GENRES = [ "Poetry", ]; -vi.mock("~/hooks/useBookFilters", () => ({ - useBookFilters: () => ({ genres: GENRES }), +// Fiction gives 100 books, Fantasy 90, and so on +const OPTIONS = GENRES.map((value, index) => ({ + value, + count: 100 - index * 10, })); // Shows the genres in the URL so tests can assert what was written to it. @@ -30,17 +33,20 @@ function SearchParamProbe() { return

{searchParams.getAll("genres").join(",")}

; } -const Stub = createRoutesStub([ - { - path: "/", - Component: () => ( - <> - - - - ), - }, -]); +function renderFilter(url: string, options: FilterOption[] = OPTIONS) { + const Stub = createRoutesStub([ + { + path: "/", + Component: () => ( + <> + + + + ), + }, + ]); + render(); +} // The labels of the shown checkboxes, in order function shownGenres() { @@ -51,7 +57,7 @@ function shownGenres() { describe("GenreFilter", () => { it("shows the 8 most common genres", () => { - render(); + renderFilter("/"); expect(shownGenres()).toEqual(GENRES.slice(0, 8)); expect( @@ -61,7 +67,7 @@ describe("GenreFilter", () => { it("keeps the order of the genres when one is checked", async () => { const user = userEvent.setup(); - render(); + renderFilter("/"); await user.click(screen.getByRole("checkbox", { name: "Mystery" })); @@ -73,7 +79,7 @@ describe("GenreFilter", () => { it("shows a selected genre that is not among the most common", async () => { const user = userEvent.setup(); - render(); + renderFilter("/?genres=Poetry"); const poetry = screen.getByRole("checkbox", { name: "Poetry" }); expect(poetry).toBeChecked(); @@ -90,7 +96,7 @@ describe("GenreFilter", () => { const user = userEvent.setup(); const maxGenres = Array.from({ length: MAX_GENRES }, (_, i) => `Genre${i}`); const query = maxGenres.map((genre) => `genres=${genre}`).join("&"); - render(); + renderFilter(`/?${query}`); await user.click(screen.getByRole("checkbox", { name: "Fiction" })); @@ -104,7 +110,7 @@ describe("GenreFilter", () => { const user = userEvent.setup(); const maxGenres = Array.from({ length: MAX_GENRES }, (_, i) => `Genre${i}`); const query = maxGenres.map((genre) => `genres=${genre}`).join("&"); - render(); + renderFilter(`/?${query}`); await user.click(screen.getByRole("checkbox", { name: "Genre0" })); @@ -115,9 +121,44 @@ describe("GenreFilter", () => { ); }); + it("shows the number of books for each genre", () => { + renderFilter("/"); + + expect( + screen.getByRole("checkbox", { name: "Fiction" }), + ).toHaveAccessibleDescription("100 books"); + expect( + screen.getByRole("checkbox", { name: "Historical" }), + ).toHaveAccessibleDescription("30 books"); + }); + + it("shows a selected genre without books for the search with 0 books", async () => { + const user = userEvent.setup(); + renderFilter("/?genres=Horror"); + + const horror = screen.getByRole("checkbox", { name: "Horror" }); + expect(horror).toBeChecked(); + expect(horror).toHaveAccessibleDescription("0 books"); + + // It is also shown among all genres, so it can be unchecked from there + await user.click( + screen.getByRole("button", { name: "Show all 10 genres" }), + ); + expect(shownGenres()).toEqual(["Horror", ...GENRES]); + }); + + it("has no show all button when all genres fit", () => { + renderFilter("/", OPTIONS.slice(0, 3)); + + expect(shownGenres()).toEqual(GENRES.slice(0, 3)); + expect( + screen.queryByRole("button", { name: /Show all/ }), + ).not.toBeInTheDocument(); + }); + it("searches all genres after clicking show all", async () => { const user = userEvent.setup(); - render(); + renderFilter("/"); await user.click( screen.getByRole("button", { name: "Show all 10 genres" }), diff --git a/frontend/app/components/books/GenreFilter/GenreFilter.tsx b/frontend/app/components/books/GenreFilter/GenreFilter.tsx index 1a1f0656..d26f6211 100644 --- a/frontend/app/components/books/GenreFilter/GenreFilter.tsx +++ b/frontend/app/components/books/GenreFilter/GenreFilter.tsx @@ -1,5 +1,7 @@ import { useId, useState } from "react"; import { useSearchParams } from "react-router"; +import type { FilterOption } from "~/api/types"; +import { FilterOptionCount } from "~/components/books/FilterOptionCount/FilterOptionCount"; import { Button } from "~/components/ui/Button"; import { Checkbox } from "~/components/ui/Checkbox"; import { @@ -11,16 +13,19 @@ import { } from "~/components/ui/Field"; import { Input } from "~/components/ui/Input"; import { toast } from "~/components/ui/Toast"; -import { useBookFilters } from "~/hooks/useBookFilters"; import { useBookSearchParams } from "~/hooks/useBookSearchParams"; import { MAX_GENRES } from "~/lib/constants"; const TOP_GENRES_COUNT = 8; -function GenreFilter() { +interface GenreFilterProps { + // The genres that give results for the current search, most books first + options: FilterOption[]; +} + +function GenreFilter({ options }: GenreFilterProps) { const [, setSearchParams] = useSearchParams(); const { filters } = useBookSearchParams(); - const { genres } = useBookFilters(); const [showAll, setShowAll] = useState(false); const [search, setSearch] = useState(""); @@ -30,13 +35,19 @@ function GenreFilter() { const selected = filters.genres ?? []; + const counts = new Map(options.map(({ value, count }) => [value, count])); + const genres = options.map((option) => option.value); const topGenres = genres.slice(0, TOP_GENRES_COUNT); + // A selected genre is missing from the options when it gives no books for + // the search. It is still shown with 0 books, so it can be unchecked + const missingGenres = selected.filter((genre) => !counts.has(genre)); + // The most common genres keep their order, so checking one doesn't move the // list. Selected genres outside them are added first, so they can be // unchecked. "Show all" shows every genre that matches the search instead const shownGenres = showAll - ? genres.filter((genre) => + ? [...missingGenres, ...genres].filter((genre) => genre.toLowerCase().includes(search.trim().toLowerCase()), ) : [...selected.filter((genre) => !topGenres.includes(genre)), ...topGenres]; @@ -85,10 +96,15 @@ function GenreFilter() { id={`${baseId}-${index}`} checked={selected.includes(genre)} onCheckedChange={(checked) => toggleGenre(genre, checked)} + aria-describedby={`${baseId}-${index}-count`} /> {genre} + ))} @@ -97,18 +113,20 @@ function GenreFilter() {

No genres found.

)} - + {(showAll || genres.length > TOP_GENRES_COUNT) && ( + + )} ); } diff --git a/frontend/app/components/books/RadioFilter/RadioFilter.test.tsx b/frontend/app/components/books/RadioFilter/RadioFilter.test.tsx index b64995ff..af65bad7 100644 --- a/frontend/app/components/books/RadioFilter/RadioFilter.test.tsx +++ b/frontend/app/components/books/RadioFilter/RadioFilter.test.tsx @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { createRoutesStub, useSearchParams } from "react-router"; +import type { FilterOption } from "~/api/types"; import { RadioFilter } from "~/components/books/RadioFilter/RadioFilter"; // Sorted by book count, like the API returns them @@ -28,7 +29,13 @@ function shownOptions() { .map((label) => label.textContent); } -function renderFilter(url: string, options = LANGUAGES) { +// English gives 70 books, Arabic 60, and so on +const OPTIONS = LANGUAGES.map((value, index) => ({ + value, + count: 70 - index * 10, +})); + +function renderFilter(url: string, options: FilterOption[] = OPTIONS) { const Stub = createRoutesStub([ { path: "/", @@ -88,6 +95,25 @@ describe("RadioFilter", () => { expect(screen.getByRole("radio", { name: "Portuguese" })).toBeChecked(); }); + it("shows the number of books for each option, but not for any", () => { + renderFilter("/"); + + expect( + screen.getByRole("radio", { name: "English" }), + ).toHaveAccessibleDescription("70 books"); + expect( + screen.getByRole("radio", { name: "Any" }), + ).not.toHaveAccessibleDescription(); + }); + + it("shows a chosen option without books for the search with 0 books", () => { + renderFilter("/?language=Norwegian"); + + const norwegian = screen.getByRole("radio", { name: "Norwegian" }); + expect(norwegian).toBeChecked(); + expect(norwegian).toHaveAccessibleDescription("0 books"); + }); + it("searches all options after clicking show all", async () => { const user = userEvent.setup(); renderFilter("/"); @@ -104,7 +130,7 @@ describe("RadioFilter", () => { }); it("has no show all button when all options fit", () => { - renderFilter("/", ["English", "French"]); + renderFilter("/", OPTIONS.slice(0, 2)); expect( screen.queryByRole("button", { name: /Show all/ }), diff --git a/frontend/app/components/books/RadioFilter/RadioFilter.tsx b/frontend/app/components/books/RadioFilter/RadioFilter.tsx index 114a052b..4407e0c8 100644 --- a/frontend/app/components/books/RadioFilter/RadioFilter.tsx +++ b/frontend/app/components/books/RadioFilter/RadioFilter.tsx @@ -1,5 +1,7 @@ import { useId, useState } from "react"; import { useSearchParams } from "react-router"; +import type { FilterOption } from "~/api/types"; +import { FilterOptionCount } from "~/components/books/FilterOptionCount/FilterOptionCount"; import { Button } from "~/components/ui/Button"; import { Field, @@ -17,7 +19,8 @@ interface RadioFilterProps { legend: string; // The search param, which is also the filter name param: "language" | "bookFormat"; - options: string[]; + // The options that give results for the current search, most books first + options: FilterOption[]; // Used in "Show all ..." and "Search ...", for example "languages" pluralName: string; } @@ -35,11 +38,18 @@ function RadioFilter({ legend, param, options, pluralName }: RadioFilterProps) { const selected = filters[param]; + const counts = new Map(options.map(({ value, count }) => [value, count])); + const values = options.map((option) => option.value); + const topOptions = values.slice(0, TOP_OPTIONS_COUNT); + + // Like in GenreFilter, a selected option that gives no books is still shown + // with 0 books + const missingOptions = selected && !counts.has(selected) ? [selected] : []; + // Like in GenreFilter, the most common options keep their order, and a // selected option outside them is added first - const topOptions = options.slice(0, TOP_OPTIONS_COUNT); const shownOptions = showAll - ? options.filter((option) => + ? [...missingOptions, ...values].filter((option) => option.toLowerCase().includes(search.trim().toLowerCase()), ) : [ @@ -80,12 +90,26 @@ function RadioFilter({ legend, param, options, pluralName }: RadioFilterProps) { onValueChange={(value) => selectOption(String(value))} className="-m-1 p-1 gap-3 max-h-72 overflow-y-auto" > - {["any", ...shownOptions].map((option, index) => ( + + + + Any + + + {shownOptions.map((option, index) => ( - + - {option === "any" ? "Any" : option} + {option} + ))} @@ -93,7 +117,7 @@ function RadioFilter({ legend, param, options, pluralName }: RadioFilterProps) {

No {pluralName} found.

)} - {options.length > TOP_OPTIONS_COUNT && ( + {(showAll || values.length > TOP_OPTIONS_COUNT) && ( )} diff --git a/frontend/app/hooks/useBookFacets.ts b/frontend/app/hooks/useBookFacets.ts new file mode 100644 index 00000000..f443e180 --- /dev/null +++ b/frontend/app/hooks/useBookFacets.ts @@ -0,0 +1,89 @@ +import { gql, type TypedDocumentNode } from "@apollo/client"; +import { useQuery } from "@apollo/client/react"; +import type { BookFilters } from "~/api/types"; +import type { + BookFacetsQuery, + BookFacetsQueryVariables, +} from "~/api/types/graphql.generated"; + +const BOOK_FACETS: TypedDocumentNode< + BookFacetsQuery, + BookFacetsQueryVariables +> = gql` + query BookFacets( + $query: String + $genres: [String!] + $language: String + $bookFormat: String + $minPages: Int + $maxPages: Int + $minRatings: Int + ) { + bookFacets( + query: $query + genres: $genres + language: $language + bookFormat: $bookFormat + minPages: $minPages + maxPages: $maxPages + minRatings: $minRatings + ) { + genres { + value + count + } + languages { + value + count + } + bookFormats { + value + count + } + } + } +`; + +/** + * The genres, languages and book formats that give results for the current + * search, with the number of books for each, most books first. + * + * Each list is counted as if its own filter wasn't set, so the user can still + * switch to another language after choosing one. Page and sort are not sent, + * so browsing the results doesn't fetch the options again. + */ +function useBookFacets({ + query, + filters, +}: { + query: string; + filters: BookFilters; +}) { + const { data, previousData, loading, error } = useQuery(BOOK_FACETS, { + variables: { + query, + genres: filters.genres, + language: filters.language, + bookFormat: filters.bookFormat, + minPages: filters.pages?.min, + maxPages: filters.pages?.max, + minRatings: filters.minRatings, + }, + }); + + // While new options load, keep the previous ones, so the filters don't + // flash or jump on every change + const facets = (data ?? previousData)?.bookFacets; + + return { + genres: facets?.genres ?? [], + languages: facets?.languages ?? [], + bookFormats: facets?.bookFormats ?? [], + // False until the first options arrive, so nothing is hidden before then + loaded: facets !== undefined, + loading, + error, + }; +} + +export { BOOK_FACETS, useBookFacets }; diff --git a/frontend/app/hooks/useBookFilters.ts b/frontend/app/hooks/useBookFilters.ts index a39d80bf..52f5aa0e 100644 --- a/frontend/app/hooks/useBookFilters.ts +++ b/frontend/app/hooks/useBookFilters.ts @@ -12,16 +12,16 @@ const BOOK_FILTERS: TypedDocumentNode< query BookFilters { genres languages - bookFormats } `; +// All genres and languages, most books first. Used by the home page. The +// filters on the books page use useBookFacets, which follows the search function useBookFilters() { const { data, loading, error } = useQuery(BOOK_FILTERS); return { genres: data?.genres ?? [], languages: data?.languages ?? [], - bookFormats: data?.bookFormats ?? [], loading, error, }; diff --git a/frontend/app/routes/books.test.tsx b/frontend/app/routes/books.test.tsx index c936da05..33d3b8d7 100644 --- a/frontend/app/routes/books.test.tsx +++ b/frontend/app/routes/books.test.tsx @@ -6,7 +6,7 @@ import SelectedBookPage from "~/routes/book/selectedBook"; import { SEARCH_BOOKS } from "~/hooks/useSearchBooks"; import { apiBook, apiSearchBooks } from "~/test/fixtures/books"; import { - bookFiltersMock, + bookFacetsMock, bookMock, defaultSearchVariables, searchBooksMock, @@ -50,7 +50,7 @@ describe("BooksPage", () => { initialEntries: ["/books"], mocks: [ searchBooksMock(), - bookFiltersMock(), + bookFacetsMock(), { ...searchBooksMock( { ...defaultSearchVariables, genres: ["Romance"] }, @@ -76,7 +76,7 @@ describe("BooksPage", () => { initialEntries: ["/books"], mocks: [ searchBooksMock(), - bookFiltersMock(), + bookFacetsMock(), { ...searchBooksMock( { ...defaultSearchVariables, genres: ["Romance"] }, @@ -136,6 +136,43 @@ describe("BooksPage", () => { ).toHaveTextContent("2"); }); + it("only shows the filter options that give results for the search", async () => { + renderRoutes(routes, { + initialEntries: ["/books?q=dune&language=English"], + mocks: [ + searchBooksMock({ + query: "dune", + language: "English", + limit: 12, + offset: 0, + }), + bookFacetsMock({ + variables: { query: "dune", language: "English" }, + genres: [{ value: "Science Fiction", count: 3 }], + languages: [ + { value: "English", count: 3 }, + { value: "French", count: 1 }, + ], + bookFormats: [], + }), + ], + }); + + expect( + await screen.findByRole("checkbox", { name: "Science Fiction" }), + ).toHaveAccessibleDescription("3 books"); + expect( + screen.queryByRole("checkbox", { name: "Fantasy" }), + ).not.toBeInTheDocument(); + expect( + screen.getByRole("radio", { name: "French" }), + ).toHaveAccessibleDescription("1 book"); + // No book format gives results, so the filter is hidden + expect( + screen.queryByRole("button", { name: "Book format" }), + ).not.toBeInTheDocument(); + }); + it.each(["0", "abc", "999999999999"])( "goes to the first page with the same search when the page in the URL is %s", async (page) => { diff --git a/frontend/app/test/mocks.ts b/frontend/app/test/mocks.ts index 859f4446..726fe818 100644 --- a/frontend/app/test/mocks.ts +++ b/frontend/app/test/mocks.ts @@ -1,9 +1,12 @@ import type { MockLink } from "@apollo/client/testing"; import type { + BookFacetsQueryVariables, BookQuery, SearchBooksQueryVariables, } from "~/api/types/graphql.generated"; +import type { FilterOption } from "~/api/types"; import { BOOK } from "~/hooks/useBook"; +import { BOOK_FACETS } from "~/hooks/useBookFacets"; import { BOOK_FILTERS } from "~/hooks/useBookFilters"; import { SEARCH_BOOKS } from "~/hooks/useSearchBooks"; import { BOOK_PAGE_LIMIT } from "~/lib/constants"; @@ -43,15 +46,59 @@ function bookMock( }; } -// The genres, languages and formats used by the filters and the home page. +// All genres and languages, used by the home page. function bookFiltersMock( genres = ["Fantasy", "Fiction", "Romance"], languages = ["English", "Norwegian"], ): MockLink.MockedResponse { return { request: { query: BOOK_FILTERS }, - result: { data: { genres, languages, bookFormats: ["Paperback"] } }, + result: { data: { genres, languages } }, }; } -export { bookFiltersMock, bookMock, defaultSearchVariables, searchBooksMock }; +// The filter options on the books page, with 10, 9, 8... books each. +// Answers every bookFacets request unless `variables` is given, since most +// tests are not about which options are shown. +function bookFacetsMock({ + genres = ["Fantasy", "Fiction", "Romance"], + languages = ["English", "Norwegian"], + bookFormats = ["Paperback"], + variables, +}: { + genres?: string[] | FilterOption[]; + languages?: string[] | FilterOption[]; + bookFormats?: string[] | FilterOption[]; + variables?: BookFacetsQueryVariables; +} = {}): MockLink.MockedResponse { + const toOptions = (options: string[] | FilterOption[]) => + options.map((option, index) => ({ + __typename: "FacetValue" as const, + ...(typeof option === "string" + ? { value: option, count: 10 - index } + : option), + })); + + return { + request: { query: BOOK_FACETS, variables: variables ?? (() => true) }, + maxUsageCount: variables ? 1 : Number.POSITIVE_INFINITY, + result: { + data: { + bookFacets: { + __typename: "BookFacets", + genres: toOptions(genres), + languages: toOptions(languages), + bookFormats: toOptions(bookFormats), + }, + }, + }, + }; +} + +export { + bookFacetsMock, + bookFiltersMock, + bookMock, + defaultSearchVariables, + searchBooksMock, +};