refactor(api): optimize caching mechanisms and improve book filtering (#372)

* refactor(api): optimize caching mechanisms and improve book filtering logic

* refactor(preferences): remove unused ExternalDocLinkComponent and enhance translate function typing

* refactor(initializer): add Duration import for improved cache management

* refactor(docker): increase MaxMetaspaceSize for improved memory management

* refactor(repository): replace findAllForSummaryByIds with findAllById

* refactor(cache): implement invalidateAppBooksQueries for improved cache management

* refactor(AppBookService): increase default page size and optimize magic shelf book resolution

* refactor(AppBookSpecification, MagicShelfBookService, TaskCancellationManager, magic-shelf-component): streamline join handling and improve memory management

* refactor(AppBookService, MagicShelfBookService): enhance book retrieval logic and improve error handling

* chore: fix formatting

* chore: fix formatting
This commit is contained in:
brios
2026-04-22 17:27:10 -04:00
committed by Zach Yale
parent 402c6f07c8
commit 3e5a6a9de8
40 changed files with 1296 additions and 429 deletions
@@ -318,7 +318,7 @@
></app-book-table>
}
@if (currentViewMode === 'grid') {
<virtual-scroller class="virtual-scroller" #scroll [items]="books" [bufferAmount]="16">
<virtual-scroller class="virtual-scroller" #scroll [items]="books" [bufferAmount]="16" (vsEnd)="onScrollEnd()">
<div
class="grid"
#container
@@ -1,4 +1,4 @@
import {signal, WritableSignal} from '@angular/core';
import {computed, signal, WritableSignal} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {ActivatedRoute, convertToParamMap, ParamMap, Router} from '@angular/router';
import {BehaviorSubject, Subject} from 'rxjs';
@@ -31,6 +31,8 @@ import {AppSettingsService} from '../../../../shared/service/app-settings.servic
import {BookBrowserComponent, EntityType} from './book-browser.component';
import {SortService} from '../../service/sort.service';
import {TranslocoService} from '@jsverse/transloco';
import {AppBooksApiService} from '../../service/app-books-api.service';
import {AppBookFilters, AppBookSort} from '../../model/app-book.model';
function makeBook(id: number, libraryId: number, title: string, addedOn: string): Book {
return {
@@ -239,6 +241,45 @@ function createHarness(options?: {
booksError: booksError.asReadonly(),
},
},
{
provide: AppBooksApiService,
useFactory: () => {
const _filters = signal<AppBookFilters>({});
const _sort = signal<AppBookSort>({field: 'addedOn', dir: 'desc'});
const _search = signal('');
const filteredSortedBooks = computed(() => {
let result = books();
const f = _filters();
if (f.libraryId) result = result.filter(b => b.libraryId === f.libraryId);
const s = _sort();
const dir = s.dir === 'asc' ? 1 : -1;
result = [...result].sort((a, b) => {
if (s.field === 'title') return dir * ((a.metadata?.title ?? '') as string).localeCompare((b.metadata?.title ?? '') as string);
if (s.field === 'addedOn') return dir * (a.addedOn ?? '').localeCompare(b.addedOn ?? '');
return 0;
});
return result;
});
return {
books: filteredSortedBooks,
totalElements: computed(() => filteredSortedBooks().length),
hasNextPage: computed(() => false),
isLoading: isBooksLoading.asReadonly(),
isFetchingNextPage: computed(() => false),
isError: computed(() => !!booksError()),
error: computed(() => booksError()),
filterOptions: computed(() => null),
setFilters: (f: AppBookFilters) => _filters.set(f),
setSort: (s: AppBookSort) => _sort.set(s),
setSearch: (s: string) => _search.set(s),
fetchNextPage: vi.fn(),
invalidate: vi.fn(),
};
},
},
{provide: BookMetadataManageService, useValue: {}},
{provide: BookDialogHelperService, useValue: {}},
{
@@ -56,8 +56,8 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {DeferredRenderState} from './deferred-render-state';
import {SortService} from '../../service/sort.service';
import {filterBooksBySearchTerm} from './filters/HeaderFilter';
import {filterBooksByFilters} from './filters/sidebar-filter';
import {AppBooksApiService} from '../../service/app-books-api.service';
import {AppBookFilters} from '../../model/app-book.model';
export enum EntityType {
LIBRARY = 'Library',
@@ -118,6 +118,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
private queryParamsService = inject(BookBrowserQueryParamsService);
private entityService = inject(BookBrowserEntityService);
private sortService = inject(SortService);
private appBooksApi = inject(AppBooksApiService);
private localStorageService = inject(LocalStorageService);
private scrollService = inject(BookBrowserScrollService);
private readonly t = inject(TranslocoService);
@@ -184,28 +185,64 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
return actions;
});
// --- Layered pipeline: each computed only recomputes when its direct inputs change ---
private readonly entityBooks = computed(() => {
const {entityId, entityType} = this.entityInfo();
return this.entityService.getBooksByEntity(this.bookService.books(), entityId, entityType);
});
private readonly searchedBooks = computed(() =>
filterBooksBySearchTerm(this.entityBooks(), this.debouncedSearchTerm())
);
private readonly filteredBooks = computed(() =>
filterBooksByFilters(this.searchedBooks(), this.selectedFilter(), this.selectedFilterMode())
);
// --- Server-side data pipeline: delegates filtering, sorting, searching to the API ---
private readonly forceExpandSeries = computed(() =>
this.queryParamsService.shouldForceExpandSeries(this.queryParamMap())
);
private readonly collapsedBooks = computed(() =>
this.seriesCollapseFilter.collapseBooks(
this.filteredBooks(), this.forceExpandSeries(), this.seriesCollapsed()
)
);
private readonly sortedBooks = computed(() =>
this.sortService.applyMultiSort(this.collapsedBooks(), this.sortCriteria())
);
/** Sync entity scope, filters, search, and sort to the API service. */
private readonly syncApiStateEffect = effect(() => {
const {entityId, entityType} = this.entityInfo();
const search = this.debouncedSearchTerm();
const sidebarFilters = this.selectedFilter();
const sortCriteria = this.sortCriteria();
const scopeFilters: AppBookFilters = {};
switch (entityType) {
case EntityType.LIBRARY:
if (!Number.isNaN(entityId)) scopeFilters.libraryId = entityId;
break;
case EntityType.SHELF:
if (!Number.isNaN(entityId)) scopeFilters.shelfId = entityId;
break;
case EntityType.MAGIC_SHELF:
if (!Number.isNaN(entityId)) scopeFilters.magicShelfId = entityId;
break;
case EntityType.UNSHELVED:
scopeFilters.unshelved = true;
break;
}
if (sidebarFilters) {
for (const [type, values] of Object.entries(sidebarFilters)) {
if (!values || values.length === 0) continue;
const strValues = values.map(String);
switch (type) {
case 'author': scopeFilters.authors = strValues; break;
case 'category': scopeFilters.category = strValues; break;
case 'series': scopeFilters.series = strValues; break;
case 'publisher': scopeFilters.publisher = strValues; break;
case 'tag': scopeFilters.tag = strValues; break;
case 'mood': scopeFilters.mood = strValues; break;
case 'narrator': scopeFilters.narrator = strValues; break;
case 'language': scopeFilters.language = strValues; break;
case 'readStatus': scopeFilters.status = strValues[0]; break;
case 'bookType': scopeFilters.fileType = strValues[0]; break;
}
}
const mode = this.selectedFilterMode();
scopeFilters.filterMode = mode === 'single' ? 'or' : mode;
}
this.appBooksApi.setFilters(scopeFilters);
this.appBooksApi.setSearch(search);
if (sortCriteria.length > 0) {
const primary = sortCriteria[0];
const dir = primary.direction === SortDirection.ASCENDING ? 'asc' as const : 'desc' as const;
this.appBooksApi.setSort({field: primary.field, dir});
}
});
// --- Deferred render: lets skeleton/refresh indicator paint before committing ---
private readonly booksRenderState = new DeferredRenderState<Book[]>();
@@ -220,7 +257,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
});
private readonly pipelineInputs = computed(() => ({
books: this.bookService.books(),
books: this.appBooksApi.books(),
entity: this.entityInfo(),
search: this.debouncedSearchTerm(),
filter: this.selectedFilter(),
@@ -238,20 +275,15 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.lastBooksContextKey = contextKey;
if (shouldRefreshInPlace) {
// Same context (sort/filter/search change within the same entity).
// Commit synchronously — the memoized computed chain is fast and
// skipping the setTimeout avoids a one-frame skeleton flash.
const requestId = this.booksRenderState.begin('refresh');
this.booksRenderState.commit(requestId, this.sortedBooks());
this.booksRenderState.commit(requestId, this.appBooksApi.books());
return;
}
// Context changed (navigation between entities or first load).
// Defer so the skeleton can paint before the pipeline evaluates.
const requestId = this.booksRenderState.begin('reset');
const timeout = globalThis.setTimeout(() => {
this.booksRenderState.commit(requestId, this.sortedBooks());
this.booksRenderState.commit(requestId, this.appBooksApi.books());
});
onCleanup(() => {
@@ -259,8 +291,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.booksRenderState.cancel(requestId);
});
});
readonly isBooksLoading = this.bookService.isBooksLoading;
readonly booksError = this.bookService.booksError;
readonly isBooksLoading = computed(() => this.appBooksApi.isLoading());
readonly booksError = this.appBooksApi.error;
readonly bookIndexById = computed(() => {
const books = this.books();
if (!books) return new Map<number, number>();
@@ -1046,7 +1078,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
attachFilesToBook(): void {
const selectedBookIds = Array.from(this.selectedBooks());
const sourceBooks = this.bookService.books().filter(book =>
const sourceBooks = (this.books() ?? []).filter(book =>
selectedBookIds.includes(book.id)
);
@@ -1084,7 +1116,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
const selectedBookIds = Array.from(this.selectedBooks());
if (selectedBookIds.length === 0) return false;
const selectedBooks = this.bookService.books().filter(book =>
const selectedBooks = (this.books() ?? []).filter(book =>
selectedBookIds.includes(book.id)
);
@@ -1106,4 +1138,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
}
onScrollEnd(): void {
if (this.appBooksApi.hasNextPage() && !this.appBooksApi.isFetchingNextPage()) {
this.appBooksApi.fetchNextPage();
}
}
}
@@ -4,6 +4,7 @@ import {Library} from '../../../model/library.model';
import {Shelf} from '../../../model/shelf.model';
import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
import {BookService} from '../../../service/book.service';
import {AppBooksApiService} from '../../../service/app-books-api.service';
import {LibraryService} from '../../../service/library.service';
import {BookRuleEvaluatorService} from '../../../../magic-shelf/service/book-rule-evaluator.service';
import {GroupRule} from '../../../../magic-shelf/component/magic-shelf-component';
@@ -11,64 +12,85 @@ import {EntityType} from '../book-browser.component';
import {Filter, FILTER_CONFIGS, FILTER_EXTRACTORS, FilterType, FilterValue, NUMERIC_ID_FILTER_TYPES, SortMode} from './book-filter.config';
import {filterBooksByFilters} from '../filters/sidebar-filter';
import {BookFilterMode} from '../../../../settings/user-management/user.service';
import {AppFilterOptions, CountedOption, LanguageOption} from '../../../model/app-book.model';
const MAX_FILTER_ITEMS = 100;
@Injectable({providedIn: 'root'})
export class BookFilterService {
private readonly bookService = inject(BookService);
private readonly appBooksApi = inject(AppBooksApiService);
private readonly libraryService = inject(LibraryService);
private readonly bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
/** Server-supported filter types -- these use /api/v1/app/filter-options data. */
private static readonly SERVER_FILTER_TYPES = new Set<FilterType>([
'author', 'category', 'series', 'publisher', 'tag', 'mood',
'narrator', 'language', 'readStatus', 'bookType',
]);
createFilterSignals(
entity: Signal<Library | Shelf | MagicShelf | null>,
entityType: Signal<EntityType>,
activeFilters: Signal<Record<string, unknown[]> | null>,
filterMode: Signal<BookFilterMode>
): Record<FilterType, Signal<Filter[]>> {
const filteredBooks = computed(() =>
this.filterBooksByEntity(this.bookService.books(), entity(), entityType())
);
const signals = {} as Record<FilterType, Signal<Filter[]>>;
// Server-backed filter types use the filter-options API
for (const type of BookFilterService.SERVER_FILTER_TYPES) {
signals[type] = computed(() => {
const options = this.appBooksApi.filterOptions();
if (!options) return [];
return this.serverOptionsToFilters(type, options);
});
}
// Client-side filter types that don't have server support use loaded books
const filteredBooks = computed(() =>
this.appBooksApi.books()
);
for (const [type, config] of Object.entries(FILTER_CONFIGS)) {
const filterType = type as Exclude<FilterType, 'library'>;
if (BookFilterService.SERVER_FILTER_TYPES.has(filterType)) continue;
signals[filterType] = computed(() => {
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), filterType);
return this.buildAndSortFilters(books, FILTER_EXTRACTORS[filterType], config.sortMode);
});
}
signals.library = computed(() => {
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), 'library');
const libraries = this.libraryService.libraries();
if (!signals.library) {
signals.library = computed(() => {
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), 'library');
const libraries = this.libraryService.libraries();
const libraryMap = new Map(
libraries
.filter(lib => lib.id !== undefined)
.map(lib => [lib.id!, lib.name])
);
const libraryMap = new Map(
libraries
.filter(lib => lib.id !== undefined)
.map(lib => [lib.id!, lib.name])
);
const filterMap = new Map<number, Filter>();
const filterMap = new Map<number, Filter>();
for (const book of books) {
if (book.libraryId == null) continue;
for (const book of books) {
if (book.libraryId == null) continue;
if (!filterMap.has(book.libraryId)) {
filterMap.set(book.libraryId, {
value: {
id: book.libraryId,
name: libraryMap.get(book.libraryId) || `Library ${book.libraryId}`
},
bookCount: 0
});
if (!filterMap.has(book.libraryId)) {
filterMap.set(book.libraryId, {
value: {
id: book.libraryId,
name: libraryMap.get(book.libraryId) || `Library ${book.libraryId}`
},
bookCount: 0
});
}
filterMap.get(book.libraryId)!.bookCount++;
}
filterMap.get(book.libraryId)!.bookCount++;
}
return this.sortFiltersByCount(Array.from(filterMap.values()));
});
return this.sortFiltersByCount(Array.from(filterMap.values()));
});
}
return signals;
}
@@ -108,6 +130,49 @@ export class BookFilterService {
return NUMERIC_ID_FILTER_TYPES.has(filterType as FilterType);
}
private serverOptionsToFilters(type: FilterType, options: AppFilterOptions): Filter[] {
switch (type) {
case 'author':
return this.countedToFilters(options.authors);
case 'category':
return this.countedToFilters(options.categories);
case 'series':
return this.countedToFilters(options.series);
case 'publisher':
return this.countedToFilters(options.publishers);
case 'tag':
return this.countedToFilters(options.tags);
case 'mood':
return this.countedToFilters(options.moods);
case 'narrator':
return this.countedToFilters(options.narrators);
case 'language':
return (options.languages ?? []).map((lang: LanguageOption) => ({
value: {id: lang.code, name: lang.label || lang.code},
bookCount: lang.count,
}));
case 'readStatus':
return (options.readStatuses ?? []).map((status: string) => ({
value: {id: status, name: status},
bookCount: 0,
}));
case 'bookType':
return (options.fileTypes ?? []).map((ft: string) => ({
value: {id: ft, name: ft},
bookCount: 0,
}));
default:
return [];
}
}
private countedToFilters(items: CountedOption[]): Filter[] {
return (items ?? []).map(item => ({
value: {id: item.name, name: item.name},
bookCount: item.count,
}));
}
private buildAndSortFilters(
books: Book[],
extractor: (book: Book) => FilterValue[],
@@ -0,0 +1,78 @@
export interface AppPageResponse<T> {
content: T[];
page: number;
size: number;
totalElements: number;
totalPages: number;
hasNext: boolean;
hasPrevious: boolean;
}
export interface AppBookSummary {
id: number;
title: string;
authors: string[];
thumbnailUrl: string | null;
readStatus: string | null;
personalRating: number | null;
seriesName: string | null;
seriesNumber: number | null;
libraryId: number;
addedOn: string | null;
lastReadTime: string | null;
readProgress: number | null;
primaryFileType: string | null;
coverUpdatedOn: string | null;
audiobookCoverUpdatedOn: string | null;
isPhysical: boolean | null;
}
export interface AppFilterOptions {
authors: CountedOption[];
languages: LanguageOption[];
readStatuses: string[];
fileTypes: string[];
categories: CountedOption[];
publishers: CountedOption[];
series: CountedOption[];
tags: CountedOption[];
moods: CountedOption[];
narrators: CountedOption[];
}
export interface CountedOption {
name: string;
count: number;
}
export interface LanguageOption {
code: string;
label: string;
count: number;
}
export interface AppBookFilters {
libraryId?: number;
shelfId?: number;
magicShelfId?: number;
unshelved?: boolean;
status?: string;
search?: string;
fileType?: string;
minRating?: number;
maxRating?: number;
authors?: string[];
language?: string[];
series?: string[];
category?: string[];
publisher?: string[];
tag?: string[];
mood?: string[];
narrator?: string[];
filterMode?: 'and' | 'or' | 'not';
}
export interface AppBookSort {
field: string;
dir: 'asc' | 'desc';
}
@@ -0,0 +1,190 @@
import {computed, inject, Injectable, signal} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {lastValueFrom} from 'rxjs';
import {injectInfiniteQuery, injectQuery, QueryClient} from '@tanstack/angular-query-experimental';
import {API_CONFIG} from '../../../core/config/api-config';
import {AuthService} from '../../../shared/service/auth.service';
import {
AppBookFilters,
AppBookSort,
AppBookSummary,
AppFilterOptions,
AppPageResponse,
} from '../model/app-book.model';
import {Book, BookType, ReadStatus} from '../model/book.model';
const PAGE_SIZE = 50;
@Injectable({providedIn: 'root'})
export class AppBooksApiService {
private readonly http = inject(HttpClient);
private readonly authService = inject(AuthService);
private readonly queryClient = inject(QueryClient);
private readonly booksUrl = `${API_CONFIG.BASE_URL}/api/v1/app/books`;
private readonly filterOptionsUrl = `${API_CONFIG.BASE_URL}/api/v1/app/filter-options`;
private readonly token = this.authService.token;
private readonly _filters = signal<AppBookFilters>({});
private readonly _sort = signal<AppBookSort>({field: 'addedOn', dir: 'desc'});
private readonly _search = signal('');
readonly booksQuery = injectInfiniteQuery(() => ({
queryKey: ['app-books', this._filters(), this._sort(), this._search()] as const,
queryFn: ({pageParam}: {pageParam: number}) => {
const params = this.buildParams(pageParam);
return lastValueFrom(this.http.get<AppPageResponse<AppBookSummary>>(this.booksUrl, {params}));
},
initialPageParam: 0,
getNextPageParam: (lastPage: AppPageResponse<AppBookSummary>) =>
lastPage.hasNext ? lastPage.page + 1 : undefined,
enabled: !!this.token(),
staleTime: 30_000,
}));
readonly filterOptionsQuery = injectQuery(() => ({
queryKey: ['app-filter-options', this._filters().libraryId, this._filters().shelfId, this._filters().magicShelfId] as const,
queryFn: () => {
const filters = this._filters();
let params = new HttpParams();
if (filters.libraryId) params = params.set('libraryId', filters.libraryId.toString());
if (filters.shelfId) params = params.set('shelfId', filters.shelfId.toString());
if (filters.magicShelfId) params = params.set('magicShelfId', filters.magicShelfId.toString());
return lastValueFrom(this.http.get<AppFilterOptions>(this.filterOptionsUrl, {params}));
},
enabled: !!this.token(),
staleTime: 60_000,
}));
/** Accumulated books from all loaded pages, mapped to the Book interface. */
readonly books = computed<Book[]>(() => {
const data = this.booksQuery.data();
if (!data) return [];
return data.pages.flatMap(page => page.content.map(summaryToBook));
});
readonly totalElements = computed(() => {
const data = this.booksQuery.data();
if (!data || data.pages.length === 0) return 0;
return data.pages[0].totalElements;
});
readonly hasNextPage = computed(() => this.booksQuery.hasNextPage());
readonly isLoading = computed(() => this.booksQuery.isPending());
readonly isFetchingNextPage = computed(() => this.booksQuery.isFetchingNextPage());
readonly isError = computed(() => this.booksQuery.isError());
readonly error = computed<string | null>(() => {
if (!this.booksQuery.isError()) return null;
const err = this.booksQuery.error();
return err instanceof Error ? err.message : 'Failed to load books';
});
readonly filterOptions = computed(() => this.filterOptionsQuery.data() ?? null);
setFilters(filters: AppBookFilters): void {
if (JSON.stringify(this._filters()) !== JSON.stringify(filters)) {
this._filters.set(filters);
}
}
setSort(sort: AppBookSort): void {
const current = this._sort();
if (current.field !== sort.field || current.dir !== sort.dir) {
this._sort.set(sort);
}
}
setSearch(search: string): void {
if (this._search() !== search) {
this._search.set(search);
}
}
fetchNextPage(): void {
this.booksQuery.fetchNextPage();
}
/** Invalidate the books query to force a refresh from the server. */
invalidate(): void {
void this.queryClient.invalidateQueries({queryKey: ['app-books']});
void this.queryClient.invalidateQueries({queryKey: ['app-filter-options']});
}
private buildParams(page: number): HttpParams {
const filters = this._filters();
const sort = this._sort();
const search = this._search();
let params = new HttpParams()
.set('page', page.toString())
.set('size', PAGE_SIZE.toString())
.set('sort', sort.field)
.set('dir', sort.dir);
if (search) params = params.set('search', search);
if (filters.libraryId) params = params.set('libraryId', filters.libraryId.toString());
if (filters.shelfId) params = params.set('shelfId', filters.shelfId.toString());
if (filters.magicShelfId) params = params.set('magicShelfId', filters.magicShelfId.toString());
if (filters.unshelved) params = params.set('unshelved', 'true');
if (filters.status) params = params.set('status', filters.status);
if (filters.fileType) params = params.set('fileType', filters.fileType);
if (filters.minRating != null) params = params.set('minRating', filters.minRating.toString());
if (filters.maxRating != null) params = params.set('maxRating', filters.maxRating.toString());
if (filters.filterMode) params = params.set('filterMode', filters.filterMode);
// Array filters: use append() to produce repeated query params (e.g. ?authors=A&authors=B)
const arrayFilters: [string, string[] | undefined][] = [
['authors', filters.authors],
['language', filters.language],
['series', filters.series],
['category', filters.category],
['publisher', filters.publisher],
['tag', filters.tag],
['mood', filters.mood],
['narrator', filters.narrator],
];
for (const [key, values] of arrayFilters) {
if (values?.length) {
for (const v of values) {
params = params.append(key, v);
}
}
}
return params;
}
}
/**
* Maps a server-side AppBookSummary to a Book-shaped object
* compatible with BookCardComponent's @Input() book property.
*/
function summaryToBook(summary: AppBookSummary): Book {
return {
id: summary.id,
libraryId: summary.libraryId,
readStatus: (summary.readStatus as ReadStatus) ?? ReadStatus.UNSET,
personalRating: summary.personalRating ?? 0,
addedOn: summary.addedOn,
lastReadTime: summary.lastReadTime,
isPhysical: summary.isPhysical ?? false,
metadata: {
bookId: summary.id,
title: summary.title,
authors: summary.authors ?? [],
seriesName: summary.seriesName,
seriesNumber: summary.seriesNumber,
coverUpdatedOn: summary.coverUpdatedOn,
audiobookCoverUpdatedOn: summary.audiobookCoverUpdatedOn,
},
primaryFile: summary.primaryFileType
? {bookType: summary.primaryFileType as BookType}
: null,
pdfProgress: summary.readProgress != null
? {page: 0, percentage: summary.readProgress}
: null,
epubProgress: null,
cbxProgress: null,
shelves: [],
} as unknown as Book;
}
@@ -100,7 +100,8 @@ describe('BookPatchService', () => {
]);
expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function));
expect(queryClient.invalidateQueries).toHaveBeenCalledTimes(2);
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['app-books']});
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['app-filter-options']});
});
it('updates cached date finished after the backend accepts the change', () => {
@@ -133,7 +134,8 @@ describe('BookPatchService', () => {
]);
expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function));
expect(queryClient.invalidateQueries).toHaveBeenCalledTimes(2);
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['app-books']});
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['app-filter-options']});
});
it('updates the cached last read timestamp without calling the backend', () => {
@@ -9,6 +9,7 @@ import {BookStatusUpdateResponse, PersonalRatingUpdateResponse} from '../model/b
import {QueryClient} from '@tanstack/angular-query-experimental';
import {BOOKS_QUERY_KEY} from './book-query-keys';
import {
invalidateAppBooksQueries,
patchBooksInCache,
patchBookFieldsInCache,
} from './book-query-cache';
@@ -270,5 +271,6 @@ export class BookPatchService {
book.id === bookId ? {...book, lastReadTime: timestamp} : book
)
);
invalidateAppBooksQueries(this.queryClient);
}
}
@@ -51,6 +51,7 @@ describe('book-query-cache', () => {
title: 'Updated Book 2'
}
});
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries');
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [firstBook]);
@@ -59,6 +60,9 @@ describe('book-query-cache', () => {
addBookToCache(queryClient, updatedSecondBook);
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([firstBook, updatedSecondBook]);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-books']});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-filter-options']});
});
it('invalidates the full books query and book detail queries', () => {
@@ -72,7 +76,8 @@ describe('book-query-cache', () => {
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(1)});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(2)});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(3)});
expect(invalidateQueriesSpy).toHaveBeenCalledTimes(5);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-books']});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-filter-options']});
});
it('patches list entries and invalidates matching detail queries', () => {
@@ -89,7 +94,8 @@ describe('book-query-cache', () => {
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([firstBook, updatedSecondBook]);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(2)});
expect(invalidateQueriesSpy).toHaveBeenCalledTimes(1);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-books']});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-filter-options']});
});
it('patches metadata, selected fields, and updater callbacks in the list cache', () => {
@@ -156,6 +162,8 @@ describe('book-query-cache', () => {
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(1)});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(2)});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(3)});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-books']});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-filter-options']});
});
it('removes detail and recommendation queries for deleted books', () => {
@@ -178,6 +186,7 @@ describe('book-query-cache', () => {
it('removes deleted books from the list cache and associated queries', () => {
const firstBook = makeBook(1);
const secondBook = makeBook(2);
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries');
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [firstBook, secondBook]);
queryClient.setQueryData(bookDetailQueryKey(1, false), firstBook);
@@ -188,6 +197,8 @@ describe('book-query-cache', () => {
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([secondBook]);
expect(queryClient.getQueryData(bookDetailQueryKey(1, false))).toBeUndefined();
expect(queryClient.getQueryData(bookRecommendationsQueryKey(1, 20))).toBeUndefined();
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-books']});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['app-filter-options']});
});
it('ignores an empty remove request', () => {
@@ -3,10 +3,19 @@ import {QueryClient} from '@tanstack/angular-query-experimental';
import {Book, BookMetadata} from '../model/book.model';
import {BOOKS_QUERY_KEY, bookDetailQueryPrefix, bookRecommendationsQueryPrefix} from './book-query-keys';
const APP_BOOKS_QUERY_PREFIX = ['app-books'] as const;
const APP_FILTER_OPTIONS_QUERY_PREFIX = ['app-filter-options'] as const;
export function invalidateAppBooksQueries(queryClient: QueryClient): void {
void queryClient.invalidateQueries({queryKey: APP_BOOKS_QUERY_PREFIX});
void queryClient.invalidateQueries({queryKey: APP_FILTER_OPTIONS_QUERY_PREFIX});
}
// --- Full invalidation (refetches from server) ---
export function invalidateBooksQuery(queryClient: QueryClient): void {
void queryClient.invalidateQueries({queryKey: BOOKS_QUERY_KEY, exact: true});
invalidateAppBooksQueries(queryClient);
}
export function invalidateBookQueries(queryClient: QueryClient, bookIds: Iterable<number>): void {
@@ -37,6 +46,7 @@ export function removeBooksFromCache(queryClient: QueryClient, bookIds: Iterable
(current ?? []).filter(book => !removedIds.has(book.id))
);
removeBookQueries(queryClient, removedIds);
invalidateAppBooksQueries(queryClient);
}
// --- Surgical patches (updates cache directly, no list refetch) ---
@@ -47,6 +57,7 @@ export function addBookToCache(queryClient: QueryClient, book: Book): void {
const exists = books.some(b => b.id === book.id);
return exists ? books.map(b => b.id === book.id ? book : b) : [...books, book];
});
invalidateAppBooksQueries(queryClient);
}
export function patchBooksInCache(queryClient: QueryClient, updatedBooks: Book[]): void {
@@ -55,6 +66,7 @@ export function patchBooksInCache(queryClient: QueryClient, updatedBooks: Book[]
(current ?? []).map(book => updatedMap.get(book.id) ?? book)
);
invalidateBookDetailQueries(queryClient, updatedBooks.map(b => b.id));
invalidateAppBooksQueries(queryClient);
}
export function patchBookMetadataInCache(queryClient: QueryClient, bookId: number, metadata: BookMetadata): void {
@@ -64,6 +76,7 @@ export function patchBookMetadataInCache(queryClient: QueryClient, bookId: numbe
)
);
invalidateBookDetailQueries(queryClient, [bookId]);
invalidateAppBooksQueries(queryClient);
}
export function patchBookInCacheWith(queryClient: QueryClient, bookId: number, updater: (book: Book) => Book): void {
@@ -71,6 +84,7 @@ export function patchBookInCacheWith(queryClient: QueryClient, bookId: number, u
(current ?? []).map(book => book.id === bookId ? updater(book) : book)
);
invalidateBookDetailQueries(queryClient, [bookId]);
invalidateAppBooksQueries(queryClient);
}
export function patchBookFieldsInCache(queryClient: QueryClient, updates: {bookId: number; fields: Partial<Book>}[]): void {
@@ -82,4 +96,5 @@ export function patchBookFieldsInCache(queryClient: QueryClient, updates: {bookI
})
);
invalidateBookDetailQueries(queryClient, updates.map(u => u.bookId));
invalidateAppBooksQueries(queryClient);
}
@@ -4,6 +4,7 @@ import {QueryClient} from '@tanstack/angular-query-experimental';
import {BOOKS_QUERY_KEY} from './book-query-keys';
import {
addBookToCache,
invalidateAppBooksQueries,
invalidateBookDetailQueries,
invalidateBooksQuery,
patchBooksInCache,
@@ -50,5 +51,6 @@ export class BookSocketService {
})
);
invalidateBookDetailQueries(this.queryClient, patches.map(p => p.id));
invalidateAppBooksQueries(this.queryClient);
}
}
@@ -18,6 +18,7 @@ import {
bookRecommendationsQueryKey,
} from './book-query-keys';
import {
invalidateAppBooksQueries,
invalidateBooksQuery,
patchBooksInCache,
removeBookQueries,
@@ -151,6 +152,7 @@ export class BookService {
shelves: book.shelves?.filter(shelf => shelf.id !== shelfId),
}))
);
invalidateAppBooksQueries(this.queryClient);
}
/*------------------ Book Retrieval ------------------*/
@@ -259,11 +261,20 @@ export class BookService {
readBook(bookId: number, reader?: 'epub-streaming', explicitBookType?: BookType): void {
const book = this.findBookById(bookId);
if (!book) {
console.error('Book not found');
if (book) {
this.navigateToReader(book, bookId, reader, explicitBookType);
return;
}
this.ensureBookDetail(bookId, false).then(detail => {
this.navigateToReader(detail, bookId, reader, explicitBookType);
}).catch(() => {
console.error('Book not found:', bookId);
});
}
private navigateToReader(book: Book, bookId: number, reader?: 'epub-streaming', explicitBookType?: BookType): void {
const bookType: BookType | undefined = explicitBookType ?? book.primaryFile?.bookType;
const isAlternativeFormat = explicitBookType && explicitBookType !== book.primaryFile?.bookType;