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:
@@ -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;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user