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