refactor(books): remove dead app-books pagination code (#2221)
This commit is contained in:
-5
@@ -2,7 +2,6 @@ import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {By} from '@angular/platform-browser';
|
||||
import {provideRouter} from '@angular/router';
|
||||
import {of, Subject} from 'rxjs';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
|
||||
@@ -43,10 +42,8 @@ describe('BookTableComponent', () => {
|
||||
let component: BookTableComponent;
|
||||
let bookSelectionService: BookSelectionService;
|
||||
let bookMetadataManageService: { toggleAllLock: ReturnType<typeof vi.fn> };
|
||||
let queryClient: { setQueryData: ReturnType<typeof vi.fn>; setQueriesData: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(() => {
|
||||
queryClient = {setQueryData: vi.fn(), setQueriesData: vi.fn()};
|
||||
bookMetadataManageService = {
|
||||
toggleAllLock: vi.fn(() => of(null)),
|
||||
};
|
||||
@@ -55,7 +52,6 @@ describe('BookTableComponent', () => {
|
||||
imports: [BookTableComponent, getTranslocoModule()],
|
||||
providers: [
|
||||
provideRouter([]),
|
||||
{provide: QueryClient, useValue: queryClient},
|
||||
{provide: MessageService, useValue: {add: vi.fn()}},
|
||||
{
|
||||
provide: UrlHelperService,
|
||||
@@ -263,7 +259,6 @@ describe('BookTableComponent', () => {
|
||||
|
||||
expect(book.metadata?.allMetadataLocked).toBe(false);
|
||||
expect(bookMetadataManageService.toggleAllLock).toHaveBeenCalledWith(new Set([1]), 'LOCK');
|
||||
expect(queryClient.setQueriesData).toHaveBeenCalledWith({queryKey: ['app-books']}, expect.any(Function));
|
||||
});
|
||||
|
||||
it('disables a row lock button while that book lock request is in flight', () => {
|
||||
|
||||
-4
@@ -6,14 +6,12 @@ import {ActivatedRoute} from '@angular/router';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
import {finalize} from 'rxjs';
|
||||
import {ColumnDef, ColumnSizingState, Header, createAngularTable, functionalUpdate, getCoreRowModel} from '@tanstack/angular-table';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {injectVirtualizer} from '@tanstack/angular-virtual';
|
||||
import {Checkbox} from '@openng/optimus-ui/checkbox';
|
||||
import {Book, BookMetadata} from '../../../model/book.model';
|
||||
import {RouteScrollPositionService} from '../../../../../shared/service/route-scroll-position.service';
|
||||
import {CoverComponent} from '../../../../../shared/components/cover/cover.component';
|
||||
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
||||
import {patchAppBooksMetadataLockInCache} from '../../../service/book-query-cache';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
import {BookSelectionService} from '../book-selection.service';
|
||||
import {BookTableRowComponent, type BookTableRowCoverPreview, type BookTableSelectionChange} from './book-table-row.component';
|
||||
@@ -92,7 +90,6 @@ export class BookTableComponent {
|
||||
protected readonly bookSelectionService = inject(BookSelectionService);
|
||||
private readonly bookMetadataManageService = inject(BookMetadataManageService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly queryClient = inject(QueryClient);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly scrollElement = viewChild<ElementRef<HTMLElement>>('scrollElement');
|
||||
@@ -295,7 +292,6 @@ export class BookTableComponent {
|
||||
)
|
||||
.subscribe({
|
||||
next: () => {
|
||||
patchAppBooksMetadataLockInCache(this.queryClient, metadata.bookId, lockAction === 'LOCK');
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: lockAction === 'LOCK' ? this.t.translate('book.table.toast.metadataLockedSummary') : this.t.translate('book.table.toast.metadataUnlockedSummary'),
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
import {BookType} from './book.model';
|
||||
|
||||
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;
|
||||
primaryFileId: number | null;
|
||||
primaryFileType: BookType | null;
|
||||
primaryFileName: string | null;
|
||||
coverUpdatedOn: string | null;
|
||||
audiobookCoverUpdatedOn: string | null;
|
||||
isPhysical: boolean | null;
|
||||
publisher: string | null;
|
||||
categories: string[] | null;
|
||||
tags: string[] | null;
|
||||
moods: string[] | null;
|
||||
language: string | null;
|
||||
narrator: string | null;
|
||||
isbn13: string | null;
|
||||
isbn10: string | null;
|
||||
publishedDate: string | null;
|
||||
pageCount: number | null;
|
||||
ageRating: number | null;
|
||||
contentRating: string | null;
|
||||
metadataMatchScore: number | null;
|
||||
fileSizeKb: number | null;
|
||||
amazonRating: number | null;
|
||||
amazonReviewCount: number | null;
|
||||
goodreadsRating: number | null;
|
||||
goodreadsReviewCount: number | null;
|
||||
hardcoverRating: number | null;
|
||||
hardcoverReviewCount: number | null;
|
||||
ranobedbRating: number | null;
|
||||
lubimyczytacRating: number | null;
|
||||
audibleRating: number | null;
|
||||
audibleReviewCount: number | null;
|
||||
allMetadataLocked: boolean | null;
|
||||
}
|
||||
|
||||
export interface AppFilterOptions {
|
||||
authors: CountedOption[];
|
||||
languages: LanguageOption[];
|
||||
readStatuses: CountedOption[];
|
||||
fileTypes: CountedOption[];
|
||||
categories: CountedOption[];
|
||||
publishers: CountedOption[];
|
||||
series: CountedOption[];
|
||||
tags: CountedOption[];
|
||||
moods: CountedOption[];
|
||||
narrators: CountedOption[];
|
||||
ageRatings: CountedOption[];
|
||||
contentRatings: CountedOption[];
|
||||
matchScores: CountedOption[];
|
||||
publishedYears: CountedOption[];
|
||||
fileSizes: CountedOption[];
|
||||
personalRatings: CountedOption[];
|
||||
amazonRatings: CountedOption[];
|
||||
goodreadsRatings: CountedOption[];
|
||||
hardcoverRatings: CountedOption[];
|
||||
lubimyczytacRatings: CountedOption[];
|
||||
ranobedbRatings: CountedOption[];
|
||||
audibleRatings: CountedOption[];
|
||||
pageCounts: CountedOption[];
|
||||
shelfStatuses: CountedOption[];
|
||||
comicCharacters: CountedOption[];
|
||||
comicTeams: CountedOption[];
|
||||
comicLocations: CountedOption[];
|
||||
comicCreators: CountedOption[];
|
||||
shelves: CountedOption[];
|
||||
libraries: 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[];
|
||||
ageRating?: string[];
|
||||
contentRating?: string[];
|
||||
matchScore?: string[];
|
||||
publishedDate?: string[];
|
||||
fileSize?: string[];
|
||||
personalRating?: string[];
|
||||
amazonRating?: string[];
|
||||
goodreadsRating?: string[];
|
||||
hardcoverRating?: string[];
|
||||
lubimyczytacRating?: string[];
|
||||
ranobedbRating?: string[];
|
||||
audibleRating?: string[];
|
||||
pageCount?: string[];
|
||||
shelfStatus?: string[];
|
||||
comicCharacter?: string[];
|
||||
comicTeam?: string[];
|
||||
comicLocation?: string[];
|
||||
comicCreator?: string[];
|
||||
shelves?: string[];
|
||||
libraries?: string[];
|
||||
filterMode?: 'and' | 'or' | 'not';
|
||||
}
|
||||
|
||||
export interface AppBookSort {
|
||||
field: string;
|
||||
dir: 'asc' | 'desc';
|
||||
}
|
||||
@@ -1,328 +0,0 @@
|
||||
import {computed, inject, Injectable, signal} from '@angular/core';
|
||||
import {HttpClient, HttpParams} from '@angular/common/http';
|
||||
import {lastValueFrom, Observable} 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, BOOK_TYPES, BookFile, BookType, ReadStatus} from '../model/book.model';
|
||||
|
||||
const PAGE_SIZE = 50;
|
||||
const BOOK_TYPE_SET = new Set<BookType>(BOOK_TYPES);
|
||||
const READ_STATUSES = new Set<ReadStatus>(Object.values(ReadStatus) as ReadStatus[]);
|
||||
|
||||
@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: 5 * 60_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: 10 * 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';
|
||||
});
|
||||
|
||||
private readonly _filterOptions = computed(() => this.filterOptionsQuery.data() ?? null);
|
||||
readonly filterOptions = this._filterOptions;
|
||||
|
||||
// Individual signals for each filter type for more granular reactivity
|
||||
readonly authorOptions = computed(() => this._filterOptions()?.authors ?? []);
|
||||
readonly languageOptions = computed(() => this._filterOptions()?.languages ?? []);
|
||||
readonly categoryOptions = computed(() => this._filterOptions()?.categories ?? []);
|
||||
readonly seriesOptions = computed(() => this._filterOptions()?.series ?? []);
|
||||
readonly publisherOptions = computed(() => this._filterOptions()?.publishers ?? []);
|
||||
readonly tagOptions = computed(() => this._filterOptions()?.tags ?? []);
|
||||
readonly moodOptions = computed(() => this._filterOptions()?.moods ?? []);
|
||||
readonly narratorOptions = computed(() => this._filterOptions()?.narrators ?? []);
|
||||
readonly ageRatingOptions = computed(() => this._filterOptions()?.ageRatings ?? []);
|
||||
readonly contentRatingOptions = computed(() => this._filterOptions()?.contentRatings ?? []);
|
||||
readonly matchScoreOptions = computed(() => this._filterOptions()?.matchScores ?? []);
|
||||
readonly publishedYearOptions = computed(() => this._filterOptions()?.publishedYears ?? []);
|
||||
readonly fileSizeOptions = computed(() => this._filterOptions()?.fileSizes ?? []);
|
||||
readonly personalRatingOptions = computed(() => this._filterOptions()?.personalRatings ?? []);
|
||||
readonly amazonRatingOptions = computed(() => this._filterOptions()?.amazonRatings ?? []);
|
||||
readonly goodreadsRatingOptions = computed(() => this._filterOptions()?.goodreadsRatings ?? []);
|
||||
readonly hardcoverRatingOptions = computed(() => this._filterOptions()?.hardcoverRatings ?? []);
|
||||
readonly lubimyczytacRatingOptions = computed(() => this._filterOptions()?.lubimyczytacRatings ?? []);
|
||||
readonly ranobedbRatingOptions = computed(() => this._filterOptions()?.ranobedbRatings ?? []);
|
||||
readonly audibleRatingOptions = computed(() => this._filterOptions()?.audibleRatings ?? []);
|
||||
readonly pageCountOptions = computed(() => this._filterOptions()?.pageCounts ?? []);
|
||||
readonly shelfStatusOptions = computed(() => this._filterOptions()?.shelfStatuses ?? []);
|
||||
readonly readStatusOptions = computed(() => this._filterOptions()?.readStatuses ?? []);
|
||||
readonly fileTypeOptions = computed(() => this._filterOptions()?.fileTypes ?? []);
|
||||
readonly comicCharacterOptions = computed(() => this._filterOptions()?.comicCharacters ?? []);
|
||||
readonly comicTeamOptions = computed(() => this._filterOptions()?.comicTeams ?? []);
|
||||
readonly comicLocationOptions = computed(() => this._filterOptions()?.comicLocations ?? []);
|
||||
readonly comicCreatorOptions = computed(() => this._filterOptions()?.comicCreators ?? []);
|
||||
readonly shelfOptions = computed(() => this._filterOptions()?.shelves ?? []);
|
||||
readonly libraryOptions = computed(() => this._filterOptions()?.libraries ?? []);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
searchBooks(query: string, size = 20): Observable<AppPageResponse<AppBookSummary>> {
|
||||
const params = new HttpParams()
|
||||
.set('q', query.trim())
|
||||
.set('page', '0')
|
||||
.set('size', Math.max(1, size).toString());
|
||||
|
||||
return this.http.get<AppPageResponse<AppBookSummary>>(`${this.booksUrl}/search`, {params});
|
||||
}
|
||||
|
||||
fetchNextPage(): void {
|
||||
this.booksQuery.fetchNextPage();
|
||||
}
|
||||
|
||||
/** Fetch all book IDs matching the current filters (no pagination). */
|
||||
fetchAllBookIds(): Observable<number[]> {
|
||||
const params = this.buildFilterParams();
|
||||
return this.http.get<number[]>(`${this.booksUrl}/ids`, {params});
|
||||
}
|
||||
|
||||
/** 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 sort = this._sort();
|
||||
|
||||
return this.buildFilterParams()
|
||||
.set('page', page.toString())
|
||||
.set('size', PAGE_SIZE.toString())
|
||||
.set('sort', sort.field)
|
||||
.set('dir', sort.dir);
|
||||
}
|
||||
|
||||
private buildFilterParams(): HttpParams {
|
||||
const filters = this._filters();
|
||||
const search = this._search();
|
||||
|
||||
let params = new HttpParams();
|
||||
|
||||
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.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],
|
||||
['ageRating', filters.ageRating],
|
||||
['contentRating', filters.contentRating],
|
||||
['matchScore', filters.matchScore],
|
||||
['publishedDate', filters.publishedDate],
|
||||
['fileSize', filters.fileSize],
|
||||
['personalRating', filters.personalRating],
|
||||
['amazonRating', filters.amazonRating],
|
||||
['goodreadsRating', filters.goodreadsRating],
|
||||
['hardcoverRating', filters.hardcoverRating],
|
||||
['lubimyczytacRating', filters.lubimyczytacRating],
|
||||
['ranobedbRating', filters.ranobedbRating],
|
||||
['audibleRating', filters.audibleRating],
|
||||
['pageCount', filters.pageCount],
|
||||
['shelfStatus', filters.shelfStatus],
|
||||
['comicCharacter', filters.comicCharacter],
|
||||
['comicTeam', filters.comicTeam],
|
||||
['comicLocation', filters.comicLocation],
|
||||
['comicCreator', filters.comicCreator],
|
||||
['shelves', filters.shelves],
|
||||
['libraries', filters.libraries],
|
||||
['status', filters.status],
|
||||
['fileType', filters.fileType],
|
||||
];
|
||||
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 book browser card and table views.
|
||||
*/
|
||||
function summaryToBook(summary: AppBookSummary): Book {
|
||||
return {
|
||||
id: summary.id,
|
||||
libraryId: summary.libraryId,
|
||||
libraryName: '',
|
||||
readStatus: summaryToReadStatus(summary.readStatus),
|
||||
personalRating: summary.personalRating,
|
||||
addedOn: summary.addedOn ?? undefined,
|
||||
lastReadTime: summary.lastReadTime ?? undefined,
|
||||
isPhysical: summary.isPhysical ?? false,
|
||||
fileSizeKb: summary.fileSizeKb ?? undefined,
|
||||
metadataMatchScore: summary.metadataMatchScore,
|
||||
metadata: {
|
||||
bookId: summary.id,
|
||||
title: summary.title,
|
||||
authors: summary.authors ?? [],
|
||||
publisher: summary.publisher ?? undefined,
|
||||
seriesName: summary.seriesName ?? undefined,
|
||||
seriesNumber: summary.seriesNumber,
|
||||
categories: summary.categories ?? [],
|
||||
tags: summary.tags ?? [],
|
||||
moods: summary.moods ?? [],
|
||||
language: summary.language ?? undefined,
|
||||
narrator: summary.narrator ?? undefined,
|
||||
isbn13: summary.isbn13 ?? undefined,
|
||||
isbn10: summary.isbn10 ?? undefined,
|
||||
coverUpdatedOn: summary.coverUpdatedOn ?? undefined,
|
||||
audiobookCoverUpdatedOn: summary.audiobookCoverUpdatedOn ?? undefined,
|
||||
publishedDate: summary.publishedDate ?? undefined,
|
||||
pageCount: summary.pageCount,
|
||||
ageRating: summary.ageRating,
|
||||
contentRating: summary.contentRating,
|
||||
amazonRating: summary.amazonRating,
|
||||
amazonReviewCount: summary.amazonReviewCount,
|
||||
goodreadsRating: summary.goodreadsRating,
|
||||
goodreadsReviewCount: summary.goodreadsReviewCount,
|
||||
hardcoverRating: summary.hardcoverRating,
|
||||
hardcoverReviewCount: summary.hardcoverReviewCount,
|
||||
ranobedbRating: summary.ranobedbRating,
|
||||
lubimyczytacRating: summary.lubimyczytacRating,
|
||||
audibleRating: summary.audibleRating,
|
||||
audibleReviewCount: summary.audibleReviewCount,
|
||||
allMetadataLocked: summary.allMetadataLocked ?? false,
|
||||
},
|
||||
primaryFile: summaryToPrimaryFile(summary),
|
||||
pdfProgress: summary.readProgress != null
|
||||
? {page: 0, percentage: summary.readProgress}
|
||||
: undefined,
|
||||
shelves: [],
|
||||
};
|
||||
}
|
||||
|
||||
function summaryToPrimaryFile(summary: AppBookSummary): BookFile | undefined {
|
||||
if (summary.primaryFileId == null) return undefined;
|
||||
|
||||
const primaryFile: BookFile = {
|
||||
id: summary.primaryFileId,
|
||||
bookId: summary.id,
|
||||
extension: summaryToPrimaryFileExtension(summary),
|
||||
fileSizeKb: summary.fileSizeKb ?? undefined,
|
||||
fileName: summary.primaryFileName ?? undefined,
|
||||
};
|
||||
|
||||
const bookType = summaryToBookType(summary.primaryFileType);
|
||||
if (bookType) {
|
||||
primaryFile.bookType = bookType;
|
||||
}
|
||||
|
||||
return primaryFile;
|
||||
}
|
||||
|
||||
function summaryToBookType(value: string | null): BookType | undefined {
|
||||
return value != null && BOOK_TYPE_SET.has(value as BookType) ? value as BookType : undefined;
|
||||
}
|
||||
|
||||
function summaryToReadStatus(value: string | null): ReadStatus {
|
||||
const readStatus = value as ReadStatus;
|
||||
return value != null && READ_STATUSES.has(readStatus) ? readStatus : ReadStatus.UNREAD;
|
||||
}
|
||||
|
||||
function summaryToPrimaryFileExtension(summary: AppBookSummary): string | undefined {
|
||||
const fileName = summary.primaryFileName;
|
||||
if (fileName) {
|
||||
const dotIndex = fileName.lastIndexOf('.');
|
||||
if (dotIndex >= 0 && dotIndex < fileName.length - 1) {
|
||||
return fileName.slice(dotIndex + 1).toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
return summary.primaryFileType?.toLowerCase();
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
import {Book, BookMetadata} from '../model/book.model';
|
||||
import {
|
||||
addBookToCache,
|
||||
invalidateBookDetailQueries,
|
||||
invalidateBookQueries,
|
||||
invalidateBooksQuery,
|
||||
patchBookFieldsInCache,
|
||||
patchBookInCacheWith,
|
||||
patchBookMetadataInCache,
|
||||
patchBooksInCache,
|
||||
removeBookQueries,
|
||||
removeBooksFromCache
|
||||
} from './book-query-cache';
|
||||
import {
|
||||
BOOKS_QUERY_KEY,
|
||||
bookDetailQueryKey,
|
||||
bookDetailQueryPrefix,
|
||||
bookRecommendationsQueryKey
|
||||
} from './book-query-keys';
|
||||
|
||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Test Library',
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Book ${id}`
|
||||
},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe('book-query-cache', () => {
|
||||
let queryClient: QueryClient;
|
||||
|
||||
beforeEach(() => {
|
||||
queryClient = new QueryClient();
|
||||
});
|
||||
|
||||
it('adds new books and replaces existing entries by id', () => {
|
||||
const firstBook = makeBook(1);
|
||||
const secondBook = makeBook(2);
|
||||
const updatedSecondBook = makeBook(2, {
|
||||
libraryName: 'Updated Library',
|
||||
metadata: {
|
||||
bookId: 2,
|
||||
title: 'Updated Book 2'
|
||||
}
|
||||
});
|
||||
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [firstBook]);
|
||||
|
||||
addBookToCache(queryClient, secondBook);
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([firstBook, secondBook]);
|
||||
|
||||
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', () => {
|
||||
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
invalidateBooksQuery(queryClient);
|
||||
invalidateBookDetailQueries(queryClient, [1, 1, 2]);
|
||||
invalidateBookQueries(queryClient, [3, 3]);
|
||||
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: BOOKS_QUERY_KEY, exact: true});
|
||||
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('patches list entries and invalidates matching detail queries', () => {
|
||||
const firstBook = makeBook(1);
|
||||
const secondBook = makeBook(2);
|
||||
const updatedSecondBook = makeBook(2, {
|
||||
libraryName: 'Updated Library'
|
||||
});
|
||||
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [firstBook, secondBook]);
|
||||
|
||||
patchBooksInCache(queryClient, [updatedSecondBook]);
|
||||
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([firstBook, updatedSecondBook]);
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(2)});
|
||||
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', () => {
|
||||
const firstBook = makeBook(1, {
|
||||
metadata: {
|
||||
bookId: 1,
|
||||
title: 'Original Title',
|
||||
authors: ['Old Author']
|
||||
}
|
||||
});
|
||||
const secondBook = makeBook(2, {
|
||||
metadata: {
|
||||
bookId: 2,
|
||||
title: 'Second'
|
||||
},
|
||||
libraryName: 'Library A'
|
||||
});
|
||||
const thirdBook = makeBook(3, {
|
||||
metadata: {
|
||||
bookId: 3,
|
||||
title: 'Third'
|
||||
}
|
||||
});
|
||||
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [firstBook, secondBook, thirdBook]);
|
||||
|
||||
const updatedMetadata: BookMetadata = {
|
||||
bookId: 1,
|
||||
title: 'Updated Title'
|
||||
};
|
||||
|
||||
patchBookMetadataInCache(queryClient, 1, updatedMetadata);
|
||||
patchBookFieldsInCache(queryClient, [
|
||||
{bookId: 2, fields: {libraryName: 'Updated Library'}},
|
||||
{bookId: 3, fields: {personalRating: 4}}
|
||||
]);
|
||||
patchBookInCacheWith(queryClient, 1, book => ({
|
||||
...book,
|
||||
metadata: {
|
||||
...(book.metadata ?? {bookId: book.id}),
|
||||
authors: ['New Author']
|
||||
}
|
||||
}));
|
||||
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([
|
||||
{
|
||||
...firstBook,
|
||||
metadata: {
|
||||
...firstBook.metadata,
|
||||
title: 'Updated Title',
|
||||
authors: ['New Author']
|
||||
}
|
||||
},
|
||||
{
|
||||
...secondBook,
|
||||
libraryName: 'Updated Library'
|
||||
},
|
||||
{
|
||||
...thirdBook,
|
||||
personalRating: 4
|
||||
}
|
||||
]);
|
||||
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', () => {
|
||||
const firstBook = makeBook(1);
|
||||
const secondBook = makeBook(2);
|
||||
|
||||
queryClient.setQueryData(bookDetailQueryKey(1, false), firstBook);
|
||||
queryClient.setQueryData(bookDetailQueryKey(1, true), firstBook);
|
||||
queryClient.setQueryData(bookRecommendationsQueryKey(1, 20), [secondBook]);
|
||||
queryClient.setQueryData(bookDetailQueryKey(2, false), secondBook);
|
||||
|
||||
removeBookQueries(queryClient, [1]);
|
||||
|
||||
expect(queryClient.getQueryData(bookDetailQueryKey(1, false))).toBeUndefined();
|
||||
expect(queryClient.getQueryData(bookDetailQueryKey(1, true))).toBeUndefined();
|
||||
expect(queryClient.getQueryData(bookRecommendationsQueryKey(1, 20))).toBeUndefined();
|
||||
expect(queryClient.getQueryData(bookDetailQueryKey(2, false))).toEqual(secondBook);
|
||||
});
|
||||
|
||||
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);
|
||||
queryClient.setQueryData(bookRecommendationsQueryKey(1, 20), [secondBook]);
|
||||
|
||||
removeBooksFromCache(queryClient, [1]);
|
||||
|
||||
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', () => {
|
||||
const setQueryDataSpy = vi.spyOn(queryClient, 'setQueryData');
|
||||
const removeQueriesSpy = vi.spyOn(queryClient, 'removeQueries');
|
||||
|
||||
removeBooksFromCache(queryClient, []);
|
||||
|
||||
expect(setQueryDataSpy).not.toHaveBeenCalled();
|
||||
expect(removeQueriesSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,165 +0,0 @@
|
||||
import {InfiniteData, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
import {Book, BookMetadata} from '../model/book.model';
|
||||
import {AppBookSummary, AppPageResponse} from '../model/app-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 {
|
||||
invalidateBooksQuery(queryClient);
|
||||
invalidateBookDetailQueries(queryClient, bookIds);
|
||||
}
|
||||
|
||||
export function invalidateBookDetailQueries(queryClient: QueryClient, bookIds: Iterable<number>): void {
|
||||
for (const bookId of new Set(bookIds)) {
|
||||
void queryClient.invalidateQueries({queryKey: bookDetailQueryPrefix(bookId)});
|
||||
}
|
||||
}
|
||||
|
||||
export function removeBookQueries(queryClient: QueryClient, bookIds: Iterable<number>): void {
|
||||
for (const bookId of new Set(bookIds)) {
|
||||
queryClient.removeQueries({queryKey: bookDetailQueryPrefix(bookId)});
|
||||
queryClient.removeQueries({queryKey: bookRecommendationsQueryPrefix(bookId)});
|
||||
}
|
||||
}
|
||||
|
||||
export function removeBooksFromCache(queryClient: QueryClient, bookIds: Iterable<number>): void {
|
||||
const removedIds = new Set(bookIds);
|
||||
if (removedIds.size === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||
(current ?? []).filter(book => !removedIds.has(book.id))
|
||||
);
|
||||
removeBookQueries(queryClient, removedIds);
|
||||
invalidateAppBooksQueries(queryClient);
|
||||
}
|
||||
|
||||
// --- Surgical patches (updates cache directly, no list refetch) ---
|
||||
|
||||
export function addBookToCache(queryClient: QueryClient, book: Book): void {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current => {
|
||||
const books = current ?? [];
|
||||
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 {
|
||||
const updatedMap = new Map(updatedBooks.map(book => [book.id, book]));
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||
(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 {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||
(current ?? []).map(book =>
|
||||
book.id === bookId ? {...book, metadata} : book
|
||||
)
|
||||
);
|
||||
invalidateBookDetailQueries(queryClient, [bookId]);
|
||||
invalidateAppBooksQueries(queryClient);
|
||||
}
|
||||
|
||||
export function patchBookInCacheWith(queryClient: QueryClient, bookId: number, updater: (book: Book) => Book): void {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||
(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 {
|
||||
const updateMap = new Map(updates.map(u => [u.bookId, u.fields]));
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||
(current ?? []).map(book => {
|
||||
const fields = updateMap.get(book.id);
|
||||
return fields ? {...book, ...fields} : book;
|
||||
})
|
||||
);
|
||||
invalidateBookDetailQueries(queryClient, updates.map(u => u.bookId));
|
||||
invalidateAppBooksQueries(queryClient);
|
||||
}
|
||||
|
||||
export function patchAppBooksCoverInCache(
|
||||
queryClient: QueryClient,
|
||||
patches: {id: number; coverUpdatedOn?: string | null; audiobookCoverUpdatedOn?: string | null}[]
|
||||
): void {
|
||||
if (patches.length === 0) return;
|
||||
const patchMap = new Map(patches.map(p => [p.id, p]));
|
||||
|
||||
queryClient.setQueriesData<InfiniteData<AppPageResponse<AppBookSummary>>>(
|
||||
{queryKey: APP_BOOKS_QUERY_PREFIX},
|
||||
(current) => {
|
||||
if (!current) return current;
|
||||
return {
|
||||
...current,
|
||||
pages: current.pages.map(page => ({
|
||||
...page,
|
||||
content: page.content.map(summary => {
|
||||
const patch = patchMap.get(summary.id);
|
||||
if (!patch) return summary;
|
||||
return {
|
||||
...summary,
|
||||
...('coverUpdatedOn' in patch ? {coverUpdatedOn: patch.coverUpdatedOn ?? null} : {}),
|
||||
...('audiobookCoverUpdatedOn' in patch ? {audiobookCoverUpdatedOn: patch.audiobookCoverUpdatedOn ?? null} : {}),
|
||||
};
|
||||
})
|
||||
}))
|
||||
};
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export function patchAppBooksMetadataLockInCache(queryClient: QueryClient, bookId: number, allMetadataLocked: boolean): void {
|
||||
// Do not create the legacy full-books cache when only the paginated app-books cache exists.
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||
current?.map(book =>
|
||||
book.id === bookId
|
||||
? {
|
||||
...book,
|
||||
metadata: {
|
||||
...(book.metadata ?? {bookId}),
|
||||
allMetadataLocked,
|
||||
},
|
||||
}
|
||||
: book
|
||||
) ?? current
|
||||
);
|
||||
|
||||
queryClient.setQueriesData<InfiniteData<AppPageResponse<AppBookSummary>>>(
|
||||
{queryKey: APP_BOOKS_QUERY_PREFIX},
|
||||
current => {
|
||||
if (!current) return current;
|
||||
|
||||
return {
|
||||
...current,
|
||||
pages: current.pages.map(page => ({
|
||||
...page,
|
||||
content: page.content.map(summary =>
|
||||
summary.id === bookId ? {...summary, allMetadataLocked} : summary
|
||||
),
|
||||
})),
|
||||
};
|
||||
}
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user