refactor(books): migrate services off the old book cache (#2218)
This commit is contained in:
@@ -284,9 +284,6 @@ describe('BookFileService', () => {
|
||||
const sourceBook = buildBook(20, {
|
||||
alternativeFormats: [buildAdditionalFile(201, {bookId: 20, fileName: 'source.epub'})],
|
||||
});
|
||||
const placeholderNewBook = buildBook(21, {
|
||||
metadata: {title: 'Placeholder'},
|
||||
});
|
||||
const response: DetachBookFileResponse = {
|
||||
sourceBook: buildBook(20, {alternativeFormats: []}),
|
||||
newBook: buildBook(21, {
|
||||
@@ -295,7 +292,7 @@ describe('BookFileService', () => {
|
||||
}),
|
||||
};
|
||||
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [sourceBook, placeholderNewBook]);
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [sourceBook]);
|
||||
|
||||
service.detachBookFile(20, 201, true).subscribe(result => {
|
||||
expect(result).toEqual(response);
|
||||
|
||||
@@ -10,7 +10,7 @@ import {CacheStorageService} from '../../../shared/service/cache-storage.service
|
||||
import {LocalSettingsService} from '../../../shared/service/local-settings.service';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {patchBookInCacheWith, patchBooksInCache, removeBooksFromCache} from './book-query-cache';
|
||||
import {patchAttachedBookFilesInCache, patchBookInCacheWith, upsertBooksInCache} from './legacy-book-cache';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
@@ -168,7 +168,7 @@ export class BookFileService {
|
||||
detachBookFile(bookId: number, fileId: number, copyMetadata: boolean): Observable<DetachBookFileResponse> {
|
||||
return this.http.post<DetachBookFileResponse>(`${this.url}/${bookId}/files/${fileId}/detach`, {copyMetadata}).pipe(
|
||||
tap(response => {
|
||||
patchBooksInCache(this.queryClient, [response.sourceBook, response.newBook]);
|
||||
upsertBooksInCache(this.queryClient, [response.sourceBook, response.newBook]);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('metadata.viewer.toast.detachFileSuccessSummary'),
|
||||
@@ -196,8 +196,11 @@ export class BookFileService {
|
||||
moveFiles
|
||||
}).pipe(
|
||||
tap(response => {
|
||||
patchBooksInCache(this.queryClient, [response.updatedBook]);
|
||||
removeBooksFromCache(this.queryClient, response.deletedSourceBookIds);
|
||||
patchAttachedBookFilesInCache(
|
||||
this.queryClient,
|
||||
response.updatedBook,
|
||||
response.deletedSourceBookIds,
|
||||
);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.bookService.toast.filesAttachedSummary'),
|
||||
|
||||
@@ -86,22 +86,43 @@ describe('BookMetadataManageService', () => {
|
||||
it('toggles cached metadata lock fields for successful bulk lock updates', () => {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [
|
||||
makeBook(1, {titleLocked: false, authorsLocked: false}),
|
||||
makeBook(2, {titleLocked: false, authorsLocked: false}),
|
||||
]);
|
||||
|
||||
service.toggleFieldLocks([1], {title: 'LOCK', authorsLocked: 'LOCK'}).subscribe();
|
||||
service.toggleFieldLocks([1, 2], {titleLocked: 'LOCK', authorsLocked: 'UNLOCK', thumbnailLocked: 'LOCK'}).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/metadata/toggle-field-locks'));
|
||||
expect(request.request.method).toBe('PUT');
|
||||
expect(request.request.body).toEqual({
|
||||
bookIds: [1],
|
||||
fieldActions: {title: 'LOCK', authorsLocked: 'LOCK'},
|
||||
bookIds: [1, 2],
|
||||
fieldActions: {titleLocked: 'LOCK', authorsLocked: 'UNLOCK', thumbnailLocked: 'LOCK'},
|
||||
});
|
||||
request.flush(null);
|
||||
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)?.[0].metadata).toMatchObject({
|
||||
titleLocked: true,
|
||||
authorsLocked: true,
|
||||
});
|
||||
const books = queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)!;
|
||||
expect(books).toHaveLength(2);
|
||||
for (const book of books) {
|
||||
expect(book.metadata).toMatchObject({titleLocked: true, authorsLocked: false, coverLocked: true});
|
||||
}
|
||||
});
|
||||
|
||||
it('patches all returned metadata locks through one batch cache update', () => {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [makeBook(1), makeBook(2)]);
|
||||
|
||||
service.toggleAllLock(new Set([1, 2]), 'LOCK').subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/metadata/toggle-all-lock'));
|
||||
expect(request.request.body).toEqual({bookIds: [1, 2], lock: 'LOCK'});
|
||||
request.flush([
|
||||
{bookId: 1, title: 'Book 1', allMetadataLocked: true},
|
||||
{bookId: 2, title: 'Book 2', allMetadataLocked: true},
|
||||
]);
|
||||
|
||||
const books = queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)!;
|
||||
expect(books).toHaveLength(2);
|
||||
for (const book of books) {
|
||||
expect(book.metadata?.allMetadataLocked).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('shows an error toast when toggleFieldLocks fails', () => {
|
||||
|
||||
@@ -7,7 +7,7 @@ import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {invalidateBookQueries, invalidateBooksQuery, patchBookInCacheWith, patchBookMetadataInCache} from './book-query-cache';
|
||||
import {invalidateAllBookCaches, invalidateBooksById, patchBookMetadataInCache, patchBooksInCacheWith} from './legacy-book-cache';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
@@ -35,29 +35,25 @@ export class BookMetadataManageService {
|
||||
updateBooksMetadata(request: BulkMetadataUpdateRequest): Observable<void> {
|
||||
return this.http.put(`${this.url}/bulk-edit-metadata`, request).pipe(
|
||||
tap(() => {
|
||||
invalidateBooksQuery(this.queryClient);
|
||||
invalidateAllBookCaches(this.queryClient);
|
||||
}),
|
||||
map(() => void 0)
|
||||
);
|
||||
}
|
||||
|
||||
toggleAllLock(bookIds: Set<number>, lock: string): Observable<void> {
|
||||
toggleAllLock(bookIds: Set<number>, lock: 'LOCK' | 'UNLOCK'): Observable<void> {
|
||||
const requestBody = {
|
||||
bookIds: Array.from(bookIds),
|
||||
lock
|
||||
};
|
||||
return this.http.put<BookMetadata[]>(`${this.url}/metadata/toggle-all-lock`, requestBody).pipe(
|
||||
tap(updatedMetadataList => {
|
||||
updatedMetadataList.forEach(metadata => {
|
||||
if (metadata.bookId != null) {
|
||||
patchBookMetadataInCache(this.queryClient, metadata.bookId, metadata);
|
||||
}
|
||||
});
|
||||
patchBooksInCacheWith(this.queryClient, updatedMetadataList.map(metadata => ({
|
||||
bookId: metadata.bookId,
|
||||
updater: (book: Book) => ({...book, metadata}),
|
||||
})));
|
||||
}),
|
||||
map(() => void 0),
|
||||
catchError((error) => {
|
||||
throw error;
|
||||
})
|
||||
map(() => void 0)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -69,19 +65,14 @@ export class BookMetadataManageService {
|
||||
fieldActions
|
||||
}).pipe(
|
||||
tap(() => {
|
||||
for (const bookId of bookIdSet) {
|
||||
patchBookInCacheWith(this.queryClient, bookId, book => {
|
||||
if (!book.metadata) return book;
|
||||
const updatedMetadata = {...book.metadata} as Record<string, unknown>;
|
||||
for (const [field, action] of Object.entries(fieldActions)) {
|
||||
const lockField = field.endsWith('Locked') ? field : `${field}Locked`;
|
||||
if (lockField in updatedMetadata) {
|
||||
updatedMetadata[lockField] = action === 'LOCK';
|
||||
}
|
||||
}
|
||||
return {...book, metadata: updatedMetadata as BookMetadata};
|
||||
});
|
||||
const lockPatch: Record<string, boolean> = {};
|
||||
for (const [field, action] of Object.entries(fieldActions)) {
|
||||
lockPatch[field === 'thumbnailLocked' ? 'coverLocked' : field] = action === 'LOCK';
|
||||
}
|
||||
patchBooksInCacheWith(this.queryClient, Array.from(bookIdSet, bookId => ({
|
||||
bookId,
|
||||
updater: (book: Book) => ({...book, metadata: {...book.metadata!, ...lockPatch}}),
|
||||
})));
|
||||
}),
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
@@ -97,7 +88,7 @@ export class BookMetadataManageService {
|
||||
consolidateMetadata(metadataType: 'authors' | 'categories' | 'moods' | 'tags' | 'series' | 'publishers' | 'languages', targetValues: string[], valuesToMerge: string[]): Observable<unknown> {
|
||||
return this.http.post(`${this.url}/metadata/manage/consolidate`, {metadataType, targetValues, valuesToMerge}).pipe(
|
||||
tap(() => {
|
||||
invalidateBooksQuery(this.queryClient);
|
||||
invalidateAllBookCaches(this.queryClient);
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -105,7 +96,7 @@ export class BookMetadataManageService {
|
||||
deleteMetadata(metadataType: 'authors' | 'categories' | 'moods' | 'tags' | 'series' | 'publishers' | 'languages', valuesToDelete: string[]): Observable<unknown> {
|
||||
return this.http.post(`${this.url}/metadata/manage/delete`, {metadataType, valuesToDelete}).pipe(
|
||||
tap(() => {
|
||||
invalidateBooksQuery(this.queryClient);
|
||||
invalidateAllBookCaches(this.queryClient);
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -125,7 +116,7 @@ export class BookMetadataManageService {
|
||||
regenerateCovers(missingOnly = false): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/regenerate-covers?missingOnly=${missingOnly}`, {}).pipe(
|
||||
tap(() => {
|
||||
invalidateBooksQuery(this.queryClient);
|
||||
invalidateAllBookCaches(this.queryClient);
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -133,7 +124,7 @@ export class BookMetadataManageService {
|
||||
regenerateCover(bookId: number): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/${bookId}/regenerate-cover`, {}).pipe(
|
||||
tap(() => {
|
||||
invalidateBookQueries(this.queryClient, [bookId]);
|
||||
invalidateBooksById(this.queryClient, [bookId]);
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -145,7 +136,7 @@ export class BookMetadataManageService {
|
||||
generateCustomCover(bookId: number): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/${bookId}/generate-custom-cover`, {}).pipe(
|
||||
tap(() => {
|
||||
invalidateBookQueries(this.queryClient, [bookId]);
|
||||
invalidateBooksById(this.queryClient, [bookId]);
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -153,7 +144,7 @@ export class BookMetadataManageService {
|
||||
generateCustomCoversForBooks(bookIds: number[]): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/bulk-generate-custom-covers`, {bookIds}).pipe(
|
||||
tap(() => {
|
||||
invalidateBookQueries(this.queryClient, bookIds);
|
||||
invalidateBooksById(this.queryClient, bookIds);
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -161,7 +152,7 @@ export class BookMetadataManageService {
|
||||
regenerateCoversForBooks(bookIds: number[]): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/bulk-regenerate-covers`, {bookIds}).pipe(
|
||||
tap(() => {
|
||||
invalidateBookQueries(this.queryClient, bookIds);
|
||||
invalidateBooksById(this.queryClient, bookIds);
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -179,7 +170,7 @@ export class BookMetadataManageService {
|
||||
formData.append('file', file);
|
||||
return this.http.post<void>(`${this.url}/${bookId}/metadata/audiobook-cover/upload`, formData).pipe(
|
||||
tap(() => {
|
||||
invalidateBookQueries(this.queryClient, [bookId]);
|
||||
invalidateBooksById(this.queryClient, [bookId]);
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -191,7 +182,7 @@ export class BookMetadataManageService {
|
||||
regenerateAudiobookCover(bookId: number): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/${bookId}/regenerate-audiobook-cover`, {}).pipe(
|
||||
tap(() => {
|
||||
invalidateBookQueries(this.queryClient, [bookId]);
|
||||
invalidateBooksById(this.queryClient, [bookId]);
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -199,7 +190,7 @@ export class BookMetadataManageService {
|
||||
generateCustomAudiobookCover(bookId: number): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/${bookId}/generate-custom-audiobook-cover`, {}).pipe(
|
||||
tap(() => {
|
||||
invalidateBookQueries(this.queryClient, [bookId]);
|
||||
invalidateBooksById(this.queryClient, [bookId]);
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -217,7 +208,7 @@ export class BookMetadataManageService {
|
||||
formData.append('bookIds', bookIds.join(','));
|
||||
return this.http.post<void>(`${this.url}/bulk-upload-cover`, formData).pipe(
|
||||
tap(() => {
|
||||
invalidateBookQueries(this.queryClient, bookIds);
|
||||
invalidateBooksById(this.queryClient, bookIds);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,10 +5,19 @@ import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
|
||||
import {ReadStatus} from '../model/book.model';
|
||||
import {Book, ReadStatus} from '../model/book.model';
|
||||
import {BOOKS_QUERY_KEY} from './book-query-keys';
|
||||
import {BookPatchService} from './book-patch.service';
|
||||
|
||||
function buildBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('BookPatchService', () => {
|
||||
let service: BookPatchService;
|
||||
let httpTestingController: HttpTestingController;
|
||||
@@ -16,8 +25,6 @@ describe('BookPatchService', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
queryClient = new QueryClient();
|
||||
vi.spyOn(queryClient, 'setQueryData');
|
||||
vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
@@ -38,7 +45,13 @@ describe('BookPatchService', () => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('posts PDF progress with file progress when a book file id is provided', () => {
|
||||
function cachedBook(id: number): Book {
|
||||
return queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)!.find(book => book.id === id)!;
|
||||
}
|
||||
|
||||
it('posts PDF progress with file progress and patches the cached book', () => {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [buildBook(11, {pdfProgress: {page: 1, percentage: 2}})]);
|
||||
|
||||
service.savePdfProgress(11, 23, 74, 88).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/progress'));
|
||||
@@ -57,11 +70,12 @@ describe('BookPatchService', () => {
|
||||
});
|
||||
request.flush(null);
|
||||
|
||||
expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function));
|
||||
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['books', 'detail', 11]});
|
||||
expect(cachedBook(11).pdfProgress).toEqual({page: 23, percentage: 74});
|
||||
});
|
||||
|
||||
it('deduplicates identical EPUB progress updates before posting', () => {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [buildBook(7)]);
|
||||
|
||||
service.saveEpubProgress(7, 'epubcfi(/6/2)', 'chapter-1.xhtml', 15, 31);
|
||||
service.saveEpubProgress(7, 'epubcfi(/6/2)', 'chapter-1.xhtml', 15, 31);
|
||||
|
||||
@@ -83,28 +97,67 @@ describe('BookPatchService', () => {
|
||||
request.flush(null);
|
||||
|
||||
httpTestingController.expectNone(req => req.url.endsWith('/api/v1/books/progress'));
|
||||
expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function));
|
||||
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['books', 'detail', 7]});
|
||||
expect(cachedBook(7).epubProgress).toEqual({cfi: 'epubcfi(/6/2)', percentage: 15});
|
||||
});
|
||||
|
||||
it('patches cached progress fields when resetting kobo progress', () => {
|
||||
service.resetProgress([1, 2], ResetProgressTypes.KOBO).subscribe();
|
||||
it('clears only kobo progress on a kobo reset, ignoring the fabricated status fields', () => {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [
|
||||
buildBook(1, {
|
||||
koboProgress: {percentage: 40},
|
||||
epubProgress: {cfi: 'epubcfi(/6/2)', percentage: 15},
|
||||
readStatus: ReadStatus.READING,
|
||||
lastReadTime: '2026-02-01T00:00:00Z',
|
||||
}),
|
||||
]);
|
||||
|
||||
service.resetProgress([1], ResetProgressTypes.KOBO).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/reset-progress'));
|
||||
expect(request.request.method).toBe('POST');
|
||||
expect(request.request.params.get('type')).toBe(ResetProgressTypes.KOBO);
|
||||
expect(request.request.body).toEqual([1, 2]);
|
||||
expect(request.request.body).toEqual([1]);
|
||||
request.flush([
|
||||
{bookId: 1, readStatus: ReadStatus.UNREAD, readStatusModifiedTime: '2026-03-01T00:00:00Z', dateFinished: null},
|
||||
{bookId: 2, readStatus: ReadStatus.READING, readStatusModifiedTime: '2026-03-02T00:00:00Z', dateFinished: '2026-03-03'},
|
||||
{bookId: 1, readStatus: null, readStatusModifiedTime: null, dateFinished: null},
|
||||
]);
|
||||
|
||||
expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function));
|
||||
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['app-books']});
|
||||
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['app-filter-options']});
|
||||
const book = cachedBook(1);
|
||||
expect(book.koboProgress).toBeUndefined();
|
||||
expect(book.epubProgress).toEqual({cfi: 'epubcfi(/6/2)', percentage: 15});
|
||||
expect(book.readStatus).toBe(ReadStatus.READING);
|
||||
expect(book.lastReadTime).toBe('2026-02-01T00:00:00Z');
|
||||
});
|
||||
|
||||
it('clears reading progress and applies the returned status on a grimmory reset', () => {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [
|
||||
buildBook(1, {
|
||||
epubProgress: {cfi: 'epubcfi(/6/2)', percentage: 15},
|
||||
koboProgress: {percentage: 40},
|
||||
readStatus: ReadStatus.READ,
|
||||
dateFinished: '2026-01-01',
|
||||
lastReadTime: '2026-02-01T00:00:00Z',
|
||||
}),
|
||||
]);
|
||||
|
||||
service.resetProgress([1], ResetProgressTypes.GRIMMORY).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/reset-progress'));
|
||||
expect(request.request.params.get('type')).toBe(ResetProgressTypes.GRIMMORY);
|
||||
request.flush([
|
||||
{bookId: 1, readStatus: ReadStatus.UNREAD, readStatusModifiedTime: '2026-03-01T00:00:00Z', dateFinished: null},
|
||||
]);
|
||||
|
||||
const book = cachedBook(1);
|
||||
expect(book.epubProgress).toBeUndefined();
|
||||
expect(book.koboProgress).toEqual({percentage: 40});
|
||||
expect(book.readStatus).toBe(ReadStatus.UNREAD);
|
||||
expect(book['readStatusModifiedTime']).toBe('2026-03-01T00:00:00Z');
|
||||
expect(book.dateFinished).toBeNull();
|
||||
expect(book.lastReadTime).toBeUndefined();
|
||||
});
|
||||
|
||||
it('updates cached date finished after the backend accepts the change', () => {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [buildBook(5, {dateFinished: '2026-01-01'})]);
|
||||
|
||||
service.updateDateFinished(5, '2026-03-10').subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/progress'));
|
||||
@@ -115,11 +168,12 @@ describe('BookPatchService', () => {
|
||||
});
|
||||
request.flush(null);
|
||||
|
||||
expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function));
|
||||
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['books', 'detail', 5]});
|
||||
expect(cachedBook(5).dateFinished).toBe('2026-03-10');
|
||||
});
|
||||
|
||||
it('updates the read status for multiple books and patches cached fields', () => {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [buildBook(1), buildBook(2)]);
|
||||
|
||||
service.updateBookReadStatus([1, 2], ReadStatus.READ).subscribe();
|
||||
|
||||
const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/status'));
|
||||
@@ -133,18 +187,18 @@ describe('BookPatchService', () => {
|
||||
{bookId: 2, readStatus: ReadStatus.READ, readStatusModifiedTime: '2026-03-05T00:00:00Z', dateFinished: '2026-03-05'},
|
||||
]);
|
||||
|
||||
expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function));
|
||||
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['app-books']});
|
||||
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['app-filter-options']});
|
||||
expect(cachedBook(1)).toMatchObject({readStatus: ReadStatus.READ, dateFinished: '2026-03-04'});
|
||||
expect(cachedBook(2)).toMatchObject({readStatus: ReadStatus.READ, dateFinished: '2026-03-05'});
|
||||
});
|
||||
|
||||
it('updates the cached last read timestamp without calling the backend', () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-03-26T12:00:00Z'));
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [buildBook(3)]);
|
||||
|
||||
service.updateLastReadTime(3);
|
||||
|
||||
expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function));
|
||||
expect(cachedBook(3).lastReadTime).toBe('2026-03-26T12:00:00.000Z');
|
||||
httpTestingController.expectNone(req => req.url.includes('/api/v1/books'));
|
||||
|
||||
vi.useRealTimers();
|
||||
|
||||
@@ -7,12 +7,12 @@ import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {ResetProgressType, ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
|
||||
import {BookStatusUpdateResponse, PersonalRatingUpdateResponse} from '../model/book.model';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {applyBookQueryChangeSet} from '../data/book-query-cache';
|
||||
import {BOOKS_QUERY_KEY} from './book-query-keys';
|
||||
import {
|
||||
invalidateAppBooksQueries,
|
||||
patchBooksInCache,
|
||||
patchBookFieldsInCache,
|
||||
} from './book-query-cache';
|
||||
} from './legacy-book-cache';
|
||||
|
||||
function getResetProgressFields(type: ResetProgressType): Partial<Book> {
|
||||
if (type === ResetProgressTypes.KOREADER) {
|
||||
@@ -213,9 +213,14 @@ export class BookPatchService {
|
||||
bookId: r.bookId,
|
||||
fields: {
|
||||
...getResetProgressFields(type),
|
||||
readStatus: r.readStatus,
|
||||
readStatusModifiedTime: r.readStatusModifiedTime,
|
||||
dateFinished: r.dateFinished
|
||||
...(type === ResetProgressTypes.GRIMMORY
|
||||
? {
|
||||
readStatus: r.readStatus,
|
||||
readStatusModifiedTime: r.readStatusModifiedTime,
|
||||
dateFinished: r.dateFinished,
|
||||
lastReadTime: undefined,
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
})));
|
||||
})
|
||||
@@ -267,10 +272,10 @@ export class BookPatchService {
|
||||
updateLastReadTime(bookId: number): void {
|
||||
const timestamp = new Date().toISOString();
|
||||
this.queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||
(current ?? []).map(book =>
|
||||
current?.map(book =>
|
||||
book.id === bookId ? {...book, lastReadTime: timestamp} : book
|
||||
)
|
||||
);
|
||||
invalidateAppBooksQueries(this.queryClient);
|
||||
void applyBookQueryChangeSet(this.queryClient, {changedBookIds: [bookId]});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects, flushQueryAsync} from '../../../core/testing/query-testing';
|
||||
import type {Book, BookMetadata} from '../model/book.model';
|
||||
import type {Shelf} from '../model/shelf.model';
|
||||
import {bookQueryKeys} from '../data/book-query-keys';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {BookPatchService} from './book-patch.service';
|
||||
import {BOOKS_QUERY_KEY} from './book-query-keys';
|
||||
@@ -219,17 +220,18 @@ describe('BookService', () => {
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books')).flush(initialBooks);
|
||||
await flushBooksQuery();
|
||||
|
||||
queryClientHarness.queryClient.setQueryData(bookQueryKeys.detail(1, false), {id: 1});
|
||||
service.removeBooksFromShelf(10);
|
||||
await flushBooksQuery();
|
||||
|
||||
expect(queryClientHarness.queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([
|
||||
const reconciledBooks = [
|
||||
buildBook(1, {shelves: [untouchedShelf]}),
|
||||
buildBook(2, {shelves: []}),
|
||||
]);
|
||||
expect(service.books()).toEqual([
|
||||
buildBook(1, {shelves: [untouchedShelf]}),
|
||||
buildBook(2, {shelves: []}),
|
||||
]);
|
||||
];
|
||||
expect(queryClientHarness.queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual(reconciledBooks);
|
||||
expect(service.books()).toEqual(reconciledBooks);
|
||||
expect(queryClientHarness.queryClient.getQueryState(bookQueryKeys.detail(1, false))?.isInvalidated).toBe(true);
|
||||
expect(queryClientHarness.queryClient.getQueryState(BOOKS_QUERY_KEY)?.isInvalidated).toBe(false);
|
||||
httpTestingController.expectNone(req => req.url.endsWith('/api/v1/books'));
|
||||
});
|
||||
|
||||
it('removes the books query cache when the auth token is cleared', async () => {
|
||||
|
||||
@@ -19,12 +19,12 @@ import {
|
||||
bookDetailQueryKey,
|
||||
bookRecommendationsQueryKey,
|
||||
} from './book-query-keys';
|
||||
import {invalidateAllBookQueries} from '../data/book-query-cache';
|
||||
import {
|
||||
invalidateAppBooksQueries,
|
||||
invalidateBooksQuery,
|
||||
invalidateAllBookCaches,
|
||||
invalidateDeletedBookQueries,
|
||||
patchBooksInCache,
|
||||
removeBookQueries,
|
||||
} from './book-query-cache';
|
||||
} from './legacy-book-cache';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
@@ -154,7 +154,7 @@ export class BookService {
|
||||
shelves: book.shelves?.filter(shelf => shelf.id !== shelfId),
|
||||
}))
|
||||
);
|
||||
invalidateAppBooksQueries(this.queryClient);
|
||||
void invalidateAllBookQueries(this.queryClient);
|
||||
}
|
||||
|
||||
/*------------------ Book Retrieval ------------------*/
|
||||
@@ -197,8 +197,7 @@ export class BookService {
|
||||
return this.http.delete<BookDeletionResponse>(this.url, {params}).pipe(
|
||||
tap(response => {
|
||||
const deletedIds = response.deleted.length > 0 ? response.deleted : idList;
|
||||
invalidateBooksQuery(this.queryClient);
|
||||
removeBookQueries(this.queryClient, deletedIds);
|
||||
invalidateDeletedBookQueries(this.queryClient, deletedIds);
|
||||
|
||||
if (response.failedFileDeletions?.length > 0) {
|
||||
this.messageService.add({
|
||||
@@ -232,7 +231,7 @@ export class BookService {
|
||||
createPhysicalBook(request: CreatePhysicalBookRequest): Observable<Book> {
|
||||
return this.http.post<Book>(`${this.url}/physical`, request).pipe(
|
||||
tap(newBook => {
|
||||
invalidateBooksQuery(this.queryClient);
|
||||
invalidateAllBookCaches(this.queryClient);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.bookService.toast.physicalBookCreatedSummary'),
|
||||
|
||||
@@ -7,7 +7,7 @@ import { AudiobookInfo, AudiobookProgress } from './audiobook.model';
|
||||
import { AuthService } from '../../../shared/service/auth.service';
|
||||
import { BookFileProgress } from '../../book/model/book.model';
|
||||
import { QueryClient } from '@tanstack/angular-query-experimental';
|
||||
import { patchBookFieldsInCache } from '../../book/service/book-query-cache';
|
||||
import { patchBookFieldsInCache } from '../../book/service/legacy-book-cache';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
|
||||
Reference in New Issue
Block a user