From 25bfff3e31bc2afb49f93f493029f48f48107b20 Mon Sep 17 00:00:00 2001 From: Alex <25013571+alexhb1@users.noreply.github.com> Date: Mon, 21 Sep 2026 13:01:53 +0100 Subject: [PATCH] refactor(books): migrate services off the old book cache (#2218) --- .../book/service/book-file.service.spec.ts | 5 +- .../book/service/book-file.service.ts | 11 ++- .../book-metadata-manage.service.spec.ts | 35 +++++-- .../service/book-metadata-manage.service.ts | 61 +++++------- .../book/service/book-patch.service.spec.ts | 98 ++++++++++++++----- .../book/service/book-patch.service.ts | 19 ++-- .../book/service/book.service.spec.ts | 16 +-- .../app/features/book/service/book.service.ts | 15 ++- .../audiobook-player/audiobook.service.ts | 2 +- 9 files changed, 167 insertions(+), 95 deletions(-) diff --git a/frontend/src/app/features/book/service/book-file.service.spec.ts b/frontend/src/app/features/book/service/book-file.service.spec.ts index 4acdb78fd..193017cd8 100644 --- a/frontend/src/app/features/book/service/book-file.service.spec.ts +++ b/frontend/src/app/features/book/service/book-file.service.spec.ts @@ -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(BOOKS_QUERY_KEY, [sourceBook, placeholderNewBook]); + queryClient.setQueryData(BOOKS_QUERY_KEY, [sourceBook]); service.detachBookFile(20, 201, true).subscribe(result => { expect(result).toEqual(response); diff --git a/frontend/src/app/features/book/service/book-file.service.ts b/frontend/src/app/features/book/service/book-file.service.ts index 94c444146..7d74bce4e 100644 --- a/frontend/src/app/features/book/service/book-file.service.ts +++ b/frontend/src/app/features/book/service/book-file.service.ts @@ -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 { return this.http.post(`${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'), diff --git a/frontend/src/app/features/book/service/book-metadata-manage.service.spec.ts b/frontend/src/app/features/book/service/book-metadata-manage.service.spec.ts index 64f4d0697..b4c7972d3 100644 --- a/frontend/src/app/features/book/service/book-metadata-manage.service.spec.ts +++ b/frontend/src/app/features/book/service/book-metadata-manage.service.spec.ts @@ -86,22 +86,43 @@ describe('BookMetadataManageService', () => { it('toggles cached metadata lock fields for successful bulk lock updates', () => { queryClient.setQueryData(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(BOOKS_QUERY_KEY)?.[0].metadata).toMatchObject({ - titleLocked: true, - authorsLocked: true, - }); + const books = queryClient.getQueryData(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(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(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', () => { diff --git a/frontend/src/app/features/book/service/book-metadata-manage.service.ts b/frontend/src/app/features/book/service/book-metadata-manage.service.ts index c38076a57..d7ae4cb27 100644 --- a/frontend/src/app/features/book/service/book-metadata-manage.service.ts +++ b/frontend/src/app/features/book/service/book-metadata-manage.service.ts @@ -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 { return this.http.put(`${this.url}/bulk-edit-metadata`, request).pipe( tap(() => { - invalidateBooksQuery(this.queryClient); + invalidateAllBookCaches(this.queryClient); }), map(() => void 0) ); } - toggleAllLock(bookIds: Set, lock: string): Observable { + toggleAllLock(bookIds: Set, lock: 'LOCK' | 'UNLOCK'): Observable { const requestBody = { bookIds: Array.from(bookIds), lock }; return this.http.put(`${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; - 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 = {}; + 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 { 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 { 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 { return this.http.post(`${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 { return this.http.post(`${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 { return this.http.post(`${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 { return this.http.post(`${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 { return this.http.post(`${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(`${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 { return this.http.post(`${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 { return this.http.post(`${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(`${this.url}/bulk-upload-cover`, formData).pipe( tap(() => { - invalidateBookQueries(this.queryClient, bookIds); + invalidateBooksById(this.queryClient, bookIds); }) ); } diff --git a/frontend/src/app/features/book/service/book-patch.service.spec.ts b/frontend/src/app/features/book/service/book-patch.service.spec.ts index a7e8f86f6..4f8031f82 100644 --- a/frontend/src/app/features/book/service/book-patch.service.spec.ts +++ b/frontend/src/app/features/book/service/book-patch.service.spec.ts @@ -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 { + 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(BOOKS_QUERY_KEY)!.find(book => book.id === id)!; + } + + it('posts PDF progress with file progress and patches the cached book', () => { + queryClient.setQueryData(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(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(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(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(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(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(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(); diff --git a/frontend/src/app/features/book/service/book-patch.service.ts b/frontend/src/app/features/book/service/book-patch.service.ts index d01c50006..39ac6b649 100644 --- a/frontend/src/app/features/book/service/book-patch.service.ts +++ b/frontend/src/app/features/book/service/book-patch.service.ts @@ -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 { 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(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]}); } } diff --git a/frontend/src/app/features/book/service/book.service.spec.ts b/frontend/src/app/features/book/service/book.service.spec.ts index 4c438f47a..f55ab9362 100644 --- a/frontend/src/app/features/book/service/book.service.spec.ts +++ b/frontend/src/app/features/book/service/book.service.spec.ts @@ -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(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(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 () => { diff --git a/frontend/src/app/features/book/service/book.service.ts b/frontend/src/app/features/book/service/book.service.ts index cf257fdf3..d12092ee5 100644 --- a/frontend/src/app/features/book/service/book.service.ts +++ b/frontend/src/app/features/book/service/book.service.ts @@ -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(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 { return this.http.post(`${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'), diff --git a/frontend/src/app/features/readers/audiobook-player/audiobook.service.ts b/frontend/src/app/features/readers/audiobook-player/audiobook.service.ts index 7a511f47d..15ba7a1cf 100644 --- a/frontend/src/app/features/readers/audiobook-player/audiobook.service.ts +++ b/frontend/src/app/features/readers/audiobook-player/audiobook.service.ts @@ -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'