refactor(books): refresh paginated cache after legacy actions (#2222)

This commit is contained in:
Alex
2026-09-21 13:01:54 +01:00
committed by GitHub
parent 79ebf13be3
commit 49cc7add81
16 changed files with 216 additions and 16 deletions
@@ -170,6 +170,17 @@ describe('AuthorEditorComponent', () => {
}); });
}); });
it('sends the author name when it has actually changed', () => {
updateAuthor.mockReturnValue(new Subject<AuthorDetails>());
const component = createComponent();
component.ngOnInit();
component.form.patchValue({name: 'Augusta Ada King'});
component.onSave();
expect(updateAuthor).toHaveBeenCalledWith(9, expect.objectContaining({name: 'Augusta Ada King'}));
});
it('clears the saving flag and reports an error toast when saveMetadata fails', () => { it('clears the saving flag and reports an error toast when saveMetadata fails', () => {
updateAuthor.mockReturnValue(throwError(() => new Error('boom'))); updateAuthor.mockReturnValue(throwError(() => new Error('boom')));
@@ -10,6 +10,7 @@ import {AuthService} from '../../../shared/service/auth.service';
import {Book} from '../../book/model/book.model'; import {Book} from '../../book/model/book.model';
import {AUTHORS_QUERY_KEY} from './author-query-keys'; import {AUTHORS_QUERY_KEY} from './author-query-keys';
import {AuthorService} from './author.service'; import {AuthorService} from './author.service';
import {bookQueryKeys} from '../../book/data/book-query-keys';
function makeBook(authors?: string[]): Book { function makeBook(authors?: string[]): Book {
return { return {
@@ -183,6 +184,28 @@ describe('AuthorService', () => {
expect(errors[0]).toEqual(new Error('boom')); expect(errors[0]).toEqual(new Error('boom'));
}); });
it('refreshes embedded book author data after an author rename', () => {
service.updateAuthor(7, {name: 'Augusta Ada King'}).subscribe();
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['books'], exact: true});
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: bookQueryKeys.all()});
});
it('refreshes book caches on any author update, not just renames', () => {
service.updateAuthor(7, {description: 'Mathematician'}).subscribe();
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['books'], exact: true});
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: bookQueryKeys.all()});
});
it('refreshes the author list and book caches after deleting authors', () => {
service.deleteAuthors([7]).subscribe();
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: AUTHORS_QUERY_KEY, exact: true});
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['books'], exact: true});
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: bookQueryKeys.all()});
});
it('builds tokenized author media urls with and without cache busters', () => { it('builds tokenized author media urls with and without cache busters', () => {
expect(service.getAuthorPhotoUrl(5)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/photo?token=token-123`); expect(service.getAuthorPhotoUrl(5)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/photo?token=token-123`);
expect(service.getAuthorThumbnailUrl(5)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/thumbnail?token=token-123`); expect(service.getAuthorThumbnailUrl(5)).toBe(`${API_CONFIG.BASE_URL}/api/v1/media/author/5/thumbnail?token=token-123`);
@@ -1,7 +1,7 @@
import {computed, DestroyRef, effect, inject, Injectable} from '@angular/core'; import {computed, DestroyRef, effect, inject, Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http'; import {HttpClient, HttpHeaders} from '@angular/common/http';
import {lastValueFrom, Observable} from 'rxjs'; import {lastValueFrom, Observable} from 'rxjs';
import {map} from 'rxjs/operators'; import {map, tap} from 'rxjs/operators';
import {SseClient} from 'ngx-sse-client'; import {SseClient} from 'ngx-sse-client';
import {API_CONFIG} from '../../../core/config/api-config'; import {API_CONFIG} from '../../../core/config/api-config';
import {AuthorSummary, AuthorDetails, AuthorSearchResult, AuthorMatchRequest, AuthorUpdateRequest, AuthorPhotoResult} from '../model/author.model'; import {AuthorSummary, AuthorDetails, AuthorSearchResult, AuthorMatchRequest, AuthorUpdateRequest, AuthorPhotoResult} from '../model/author.model';
@@ -10,6 +10,7 @@ import {AuthService} from '../../../shared/service/auth.service';
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental'; import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
import {AUTHORS_QUERY_KEY} from './author-query-keys'; import {AUTHORS_QUERY_KEY} from './author-query-keys';
import {invalidateAuthorsQuery, patchAuthorInCache} from './author-query-cache'; import {invalidateAuthorsQuery, patchAuthorInCache} from './author-query-cache';
import {invalidateAllBookCaches} from '../../book/service/legacy-book-cache';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@@ -136,7 +137,9 @@ export class AuthorService {
} }
updateAuthor(authorId: number, request: AuthorUpdateRequest): Observable<AuthorDetails> { updateAuthor(authorId: number, request: AuthorUpdateRequest): Observable<AuthorDetails> {
return this.http.put<AuthorDetails>(`${this.baseUrl}/${authorId}`, request); return this.http.put<AuthorDetails>(`${this.baseUrl}/${authorId}`, request).pipe(
tap(() => invalidateAllBookCaches(this.queryClient))
);
} }
unmatchAuthors(authorIds: number[]): Observable<void> { unmatchAuthors(authorIds: number[]): Observable<void> {
@@ -144,7 +147,12 @@ export class AuthorService {
} }
deleteAuthors(authorIds: number[]): Observable<void> { deleteAuthors(authorIds: number[]): Observable<void> {
return this.http.delete<void>(this.baseUrl, {body: authorIds}); return this.http.delete<void>(this.baseUrl, {body: authorIds}).pipe(
tap(() => {
invalidateAllBookCaches(this.queryClient);
invalidateAuthorsQuery(this.queryClient);
})
);
} }
searchAuthorPhotos(authorId: number, query: string): Observable<AuthorPhotoResult> { searchAuthorPhotos(authorId: number, query: string): Observable<AuthorPhotoResult> {
@@ -8,6 +8,7 @@ import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type'
import {Book, 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';
import {shelfDefinitionQueryKeys} from '../data/shelf-definition-query-keys';
function buildBook(id: number, overrides: Partial<Book> = {}): Book { function buildBook(id: number, overrides: Partial<Book> = {}): Book {
return { return {
@@ -203,4 +204,14 @@ describe('BookPatchService', () => {
vi.useRealTimers(); vi.useRealTimers();
}); });
it('refreshes shelf counts after changing book membership', () => {
queryClient.setQueryData(shelfDefinitionQueryKeys.definitions(), []);
service.updateBookShelves(new Set([1]), new Set([7]), new Set()).subscribe();
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/books/shelves')).flush([]);
expect(queryClient.getQueryState(shelfDefinitionQueryKeys.definitions())?.isInvalidated).toBe(true);
});
}); });
@@ -13,6 +13,7 @@ import {
patchBooksInCache, patchBooksInCache,
patchBookFieldsInCache, patchBookFieldsInCache,
} from './legacy-book-cache'; } from './legacy-book-cache';
import {invalidateShelfDefinitions} from '../data/shelf-definition-query-cache';
function getResetProgressFields(type: ResetProgressType): Partial<Book> { function getResetProgressFields(type: ResetProgressType): Partial<Book> {
if (type === ResetProgressTypes.KOREADER) { if (type === ResetProgressTypes.KOREADER) {
@@ -105,6 +106,7 @@ export class BookPatchService {
return this.http.post<Book[]>(`${this.url}/shelves`, requestPayload).pipe( return this.http.post<Book[]>(`${this.url}/shelves`, requestPayload).pipe(
tap(updatedBooks => { tap(updatedBooks => {
patchBooksInCache(this.queryClient, updatedBooks); patchBooksInCache(this.queryClient, updatedBooks);
void invalidateShelfDefinitions(this.queryClient);
}) })
); );
} }
@@ -6,7 +6,11 @@ import {AuthService} from '../../../shared/service/auth.service';
import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../../core/testing/query-testing'; import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../../core/testing/query-testing';
import type {Library} from '../model/library.model'; import type {Library} from '../model/library.model';
import {BookService} from './book.service'; import {BookService} from './book.service';
import {bookQueryKeys} from '../data/book-query-keys';
import {shelfDefinitionQueryKeys} from '../data/shelf-definition-query-keys';
import {AUTHORS_QUERY_KEY} from '../../author-browser/service/author-query-keys';
import {BOOKS_QUERY_KEY} from './book-query-keys'; import {BOOKS_QUERY_KEY} from './book-query-keys';
import {SHELVES_QUERY_KEY} from './shelf-query-keys';
import {LIBRARIES_QUERY_KEY, libraryFormatCountsQueryKey} from './library-query-keys'; import {LIBRARIES_QUERY_KEY, libraryFormatCountsQueryKey} from './library-query-keys';
import {LibraryService} from './library.service'; import {LibraryService} from './library.service';
@@ -77,7 +81,7 @@ describe('LibraryService', () => {
expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: LIBRARIES_QUERY_KEY, exact: true}); expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: LIBRARIES_QUERY_KEY, exact: true});
}); });
it('invalidates library and book caches after update and delete flows', () => { it('invalidates library and book caches after updating a library', () => {
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries')).flush([]); httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries')).flush([]);
service.updateLibrary(buildLibrary({name: 'Updated'}), 4).subscribe(); service.updateLibrary(buildLibrary({name: 'Updated'}), 4).subscribe();
@@ -85,6 +89,14 @@ describe('LibraryService', () => {
expect(updateRequest.request.method).toBe('PUT'); expect(updateRequest.request.method).toBe('PUT');
updateRequest.flush(buildLibrary({id: 4, name: 'Updated'})); updateRequest.flush(buildLibrary({id: 4, name: 'Updated'}));
expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: LIBRARIES_QUERY_KEY, exact: true});
expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: BOOKS_QUERY_KEY, exact: true});
expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: bookQueryKeys.all()});
});
it('invalidates library, book, shelf, and author caches after deleting a library', () => {
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries')).flush([]);
service.deleteLibrary(4).subscribe(); service.deleteLibrary(4).subscribe();
const deleteRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries/4')); const deleteRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries/4'));
expect(deleteRequest.request.method).toBe('DELETE'); expect(deleteRequest.request.method).toBe('DELETE');
@@ -92,6 +104,10 @@ describe('LibraryService', () => {
expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: LIBRARIES_QUERY_KEY, exact: true}); expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: LIBRARIES_QUERY_KEY, exact: true});
expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: BOOKS_QUERY_KEY, exact: true}); expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: BOOKS_QUERY_KEY, exact: true});
expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: bookQueryKeys.all()});
expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: shelfDefinitionQueryKeys.all()});
expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: SHELVES_QUERY_KEY, exact: true});
expect(queryClientHarness.queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: AUTHORS_QUERY_KEY, exact: true});
expect(queryClientHarness.queryClient.removeQueries).toHaveBeenCalledWith({queryKey: libraryFormatCountsQueryKey(4), exact: true}); expect(queryClientHarness.queryClient.removeQueries).toHaveBeenCalledWith({queryKey: libraryFormatCountsQueryKey(4), exact: true});
}); });
@@ -8,8 +8,11 @@ import {Library} from '../model/library.model';
import {BookService} from './book.service'; import {BookService} from './book.service';
import {API_CONFIG} from '../../../core/config/api-config'; import {API_CONFIG} from '../../../core/config/api-config';
import {AuthService} from '../../../shared/service/auth.service'; import {AuthService} from '../../../shared/service/auth.service';
import {BOOKS_QUERY_KEY} from './book-query-keys';
import {LIBRARIES_QUERY_KEY, libraryFormatCountsQueryKey} from './library-query-keys'; import {LIBRARIES_QUERY_KEY, libraryFormatCountsQueryKey} from './library-query-keys';
import {AUTHORS_QUERY_KEY} from '../../author-browser/service/author-query-keys';
import {invalidateShelfDefinitions} from '../data/shelf-definition-query-cache';
import {invalidateAllBookCaches} from './legacy-book-cache';
import {SHELVES_QUERY_KEY} from './shelf-query-keys';
@Injectable({providedIn: 'root'}) @Injectable({providedIn: 'root'})
export class LibraryService { export class LibraryService {
@@ -80,7 +83,7 @@ export class LibraryService {
return this.http.put<Library>(`${this.url}/${id}`, lib).pipe( return this.http.put<Library>(`${this.url}/${id}`, lib).pipe(
tap(() => { tap(() => {
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true}); void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
void this.queryClient.invalidateQueries({queryKey: BOOKS_QUERY_KEY, exact: true}); invalidateAllBookCaches(this.queryClient);
}) })
); );
} }
@@ -89,7 +92,10 @@ export class LibraryService {
return this.http.delete<void>(`${this.url}/${id}`).pipe( return this.http.delete<void>(`${this.url}/${id}`).pipe(
tap(() => { tap(() => {
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true}); void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
void this.queryClient.invalidateQueries({queryKey: BOOKS_QUERY_KEY, exact: true}); invalidateAllBookCaches(this.queryClient);
void invalidateShelfDefinitions(this.queryClient);
void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true});
void this.queryClient.invalidateQueries({queryKey: AUTHORS_QUERY_KEY, exact: true});
this.queryClient.removeQueries({queryKey: libraryFormatCountsQueryKey(id), exact: true}); this.queryClient.removeQueries({queryKey: libraryFormatCountsQueryKey(id), exact: true});
}) })
); );
@@ -0,0 +1 @@
export const SHELVES_QUERY_KEY = ['shelves'] as const;
@@ -6,6 +6,8 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {createAuthServiceStub, createQueryClientHarness, flushQueryAsync, flushSignalAndQueryEffects} from '../../../core/testing/query-testing'; import {createAuthServiceStub, createQueryClientHarness, flushQueryAsync, flushSignalAndQueryEffects} from '../../../core/testing/query-testing';
import type {Book} from '../model/book.model'; import type {Book} from '../model/book.model';
import type {Shelf} from '../model/shelf.model'; import type {Shelf} from '../model/shelf.model';
import {shelfDefinitionQueryKeys} from '../data/shelf-definition-query-keys';
import {bookQueryKeys} from '../data/book-query-keys';
import {AuthService} from '../../../shared/service/auth.service'; import {AuthService} from '../../../shared/service/auth.service';
import {UserService} from '../../settings/user-management/user.service'; import {UserService} from '../../settings/user-management/user.service';
import {BookService} from './book.service'; import {BookService} from './book.service';
@@ -127,30 +129,59 @@ describe('ShelfService', () => {
expect(removeQueriesSpy).toHaveBeenCalledWith({queryKey: ['shelves']}); expect(removeQueriesSpy).toHaveBeenCalledWith({queryKey: ['shelves']});
}); });
it('invalidates shelf queries for reload/create/update/delete flows and removes books on delete', () => { it('reloads the shelves list on demand', () => {
const invalidateQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined); const invalidateQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined);
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([]); httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([]);
service.reloadShelves(); service.reloadShelves();
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['shelves'], exact: true});
});
it('invalidates shelf and shelf-definition caches when creating a shelf, without touching book caches', () => {
const invalidateQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined);
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([]);
service.createShelf(buildShelf({name: 'New Shelf'})).subscribe(); service.createShelf(buildShelf({name: 'New Shelf'})).subscribe();
const createRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')); const createRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves'));
expect(createRequest.request.method).toBe('POST'); expect(createRequest.request.method).toBe('POST');
createRequest.flush(buildShelf({id: 11, name: 'New Shelf'})); createRequest.flush(buildShelf({id: 11, name: 'New Shelf'}));
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['shelves'], exact: true});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: shelfDefinitionQueryKeys.all()});
expect(invalidateQueriesSpy).not.toHaveBeenCalledWith({queryKey: bookQueryKeys.all()});
});
it('invalidates shelf-definition and book caches when renaming a shelf', () => {
const invalidateQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined);
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([]);
service.updateShelf(buildShelf({name: 'Updated Shelf'}), 11).subscribe(); service.updateShelf(buildShelf({name: 'Updated Shelf'}), 11).subscribe();
const updateRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves/11')); const updateRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves/11'));
expect(updateRequest.request.method).toBe('PUT'); expect(updateRequest.request.method).toBe('PUT');
updateRequest.flush(buildShelf({id: 11, name: 'Updated Shelf'})); updateRequest.flush(buildShelf({id: 11, name: 'Updated Shelf'}));
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['shelves'], exact: true});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: shelfDefinitionQueryKeys.all()});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookQueryKeys.all()});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['books'], exact: true});
});
it('invalidates shelf caches and delegates book removal when deleting a shelf', () => {
const invalidateQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined);
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([]);
service.deleteShelf(11).subscribe(); service.deleteShelf(11).subscribe();
const deleteRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves/11')); const deleteRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves/11'));
expect(deleteRequest.request.method).toBe('DELETE'); expect(deleteRequest.request.method).toBe('DELETE');
deleteRequest.flush(null); deleteRequest.flush(null);
expect(invalidateQueriesSpy).toHaveBeenCalledTimes(4);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['shelves'], exact: true}); expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['shelves'], exact: true});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: shelfDefinitionQueryKeys.all()});
expect(bookService.removeBooksFromShelf).toHaveBeenCalledWith(11); expect(bookService.removeBooksFromShelf).toHaveBeenCalledWith(11);
}); });
@@ -5,13 +5,15 @@ import {tap} from 'rxjs/operators';
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental'; import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
import {Shelf} from '../model/shelf.model'; import {Shelf} from '../model/shelf.model';
import {invalidateShelfDefinitions} from '../data/shelf-definition-query-cache';
import {invalidateAllBookCaches} from './legacy-book-cache';
import {SHELVES_QUERY_KEY} from './shelf-query-keys';
import {BookService} from './book.service'; import {BookService} from './book.service';
import {API_CONFIG} from '../../../core/config/api-config'; import {API_CONFIG} from '../../../core/config/api-config';
import {Book} from '../model/book.model'; import {Book} from '../model/book.model';
import {UserService} from '../../settings/user-management/user.service'; import {UserService} from '../../settings/user-management/user.service';
import {AuthService} from '../../../shared/service/auth.service'; import {AuthService} from '../../../shared/service/auth.service';
const SHELVES_QUERY_KEY = ['shelves'] as const;
const KOBO_SHELF_NAME = 'Kobo'; const KOBO_SHELF_NAME = 'Kobo';
const KOBO_SHELF_ICON = 'pi pi-tablet'; const KOBO_SHELF_ICON = 'pi pi-tablet';
@@ -67,6 +69,7 @@ export class ShelfService {
return this.http.post<Shelf>(this.url, shelf).pipe( return this.http.post<Shelf>(this.url, shelf).pipe(
tap(() => { tap(() => {
void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true}); void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true});
void invalidateShelfDefinitions(this.queryClient);
}) })
); );
} }
@@ -75,6 +78,8 @@ export class ShelfService {
return this.http.put<Shelf>(`${this.url}/${id}`, shelf).pipe( return this.http.put<Shelf>(`${this.url}/${id}`, shelf).pipe(
tap(() => { tap(() => {
void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true}); void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true});
void invalidateShelfDefinitions(this.queryClient);
invalidateAllBookCaches(this.queryClient);
}) })
); );
} }
@@ -84,6 +89,7 @@ export class ShelfService {
tap(() => { tap(() => {
this.bookService.removeBooksFromShelf(id); this.bookService.removeBooksFromShelf(id);
void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true}); void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true});
void invalidateShelfDefinitions(this.queryClient);
}) })
); );
} }
@@ -9,6 +9,7 @@ import type {GroupRule} from '../component/magic-shelf-component';
import {BookService} from '../../book/service/book.service'; import {BookService} from '../../book/service/book.service';
import {BookRuleEvaluatorService} from './book-rule-evaluator.service'; import {BookRuleEvaluatorService} from './book-rule-evaluator.service';
import {MagicShelfService, type MagicShelf} from './magic-shelf.service'; import {MagicShelfService, type MagicShelf} from './magic-shelf.service';
import {bookQueryKeys} from '../../book/data/book-query-keys';
function buildMagicShelf(overrides: Partial<MagicShelf> = {}): MagicShelf { function buildMagicShelf(overrides: Partial<MagicShelf> = {}): MagicShelf {
return { return {
@@ -170,6 +171,26 @@ describe('MagicShelfService', () => {
request.flush(buildMagicShelf({id: 11, name: 'Magic', filterJson: JSON.stringify(group), isPublic: true})); request.flush(buildMagicShelf({id: 11, name: 'Magic', filterJson: JSON.stringify(group), isPublic: true}));
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['magicShelves'], exact: true}); expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['magicShelves'], exact: true});
expect(invalidateQueriesSpy).not.toHaveBeenCalledWith({queryKey: bookQueryKeys.collections()});
});
it('invalidates browser collections after changing an existing shelf rule', () => {
const invalidateQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined);
httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves')).flush([]);
service.saveShelf({
id: 11,
name: 'Changed',
icon: 'zap',
group: buildGroupRule({name: 'Changed'}),
}).subscribe();
httpTestingController.expectOne(req => req.url.endsWith('/api/magic-shelves')).flush(
buildMagicShelf({id: 11, name: 'Changed'}),
);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookQueryKeys.collections()});
}); });
it('invalidates shelf queries after delete', () => { it('invalidates shelf queries after delete', () => {
@@ -184,6 +205,7 @@ describe('MagicShelfService', () => {
request.flush(null); request.flush(null);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['magicShelves'], exact: true}); expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['magicShelves'], exact: true});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookQueryKeys.collections()});
}); });
it('finds shelves by id from the hydrated query state', async () => { it('finds shelves by id from the hydrated query state', async () => {
@@ -10,6 +10,7 @@ import {BookRuleEvaluatorService} from './book-rule-evaluator.service';
import {AuthService} from '../../../shared/service/auth.service'; import {AuthService} from '../../../shared/service/auth.service';
import {GroupRule} from '../component/magic-shelf-component'; import {GroupRule} from '../component/magic-shelf-component';
import {IconType} from '../../../shared/icons/icon-selection'; import {IconType} from '../../../shared/icons/icon-selection';
import {invalidateBookCollections} from '../../book/data/book-query-cache';
export interface MagicShelf { export interface MagicShelf {
id?: number | null; id?: number | null;
@@ -89,6 +90,9 @@ export class MagicShelfService {
return this.http.post<MagicShelf>(this.url, payload).pipe( return this.http.post<MagicShelf>(this.url, payload).pipe(
tap(() => { tap(() => {
void this.queryClient.invalidateQueries({queryKey: MAGIC_SHELVES_QUERY_KEY, exact: true}); void this.queryClient.invalidateQueries({queryKey: MAGIC_SHELVES_QUERY_KEY, exact: true});
if (data.id != null) {
void invalidateBookCollections(this.queryClient);
}
}) })
); );
} }
@@ -131,6 +135,7 @@ export class MagicShelfService {
return this.http.delete<void>(`${this.url}/${id}`).pipe( return this.http.delete<void>(`${this.url}/${id}`).pipe(
tap(() => { tap(() => {
void this.queryClient.invalidateQueries({queryKey: MAGIC_SHELVES_QUERY_KEY, exact: true}); void this.queryClient.invalidateQueries({queryKey: MAGIC_SHELVES_QUERY_KEY, exact: true});
void invalidateBookCollections(this.queryClient);
}) })
); );
} }
@@ -1,21 +1,27 @@
import {provideHttpClient} from '@angular/common/http'; import {provideHttpClient} from '@angular/common/http';
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {afterEach, beforeEach, describe, expect, it} from 'vitest'; import {QueryClient} from '@tanstack/angular-query-experimental';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {API_CONFIG} from '../../../core/config/api-config'; import {API_CONFIG} from '../../../core/config/api-config';
import {bookQueryKeys} from '../../book/data/book-query-keys';
import {AUTHORS_QUERY_KEY} from '../../author-browser/service/author-query-keys';
import {SidecarService} from './sidecar.service'; import {SidecarService} from './sidecar.service';
describe('SidecarService', () => { describe('SidecarService', () => {
let service: SidecarService; let service: SidecarService;
let httpTestingController: HttpTestingController; let httpTestingController: HttpTestingController;
let queryClient: QueryClient;
beforeEach(() => { beforeEach(() => {
queryClient = new QueryClient();
TestBed.configureTestingModule({ TestBed.configureTestingModule({
providers: [ providers: [
provideHttpClient(), provideHttpClient(),
provideHttpClientTesting(), provideHttpClientTesting(),
SidecarService, SidecarService,
{provide: QueryClient, useValue: queryClient},
] ]
}); });
@@ -25,6 +31,7 @@ describe('SidecarService', () => {
afterEach(() => { afterEach(() => {
httpTestingController.verify(); httpTestingController.verify();
queryClient.clear();
TestBed.resetTestingModule(); TestBed.resetTestingModule();
}); });
@@ -65,6 +72,8 @@ describe('SidecarService', () => {
}); });
it('imports a sidecar for a book', () => { it('imports a sidecar for a book', () => {
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue(undefined);
service.importFromSidecar(42).subscribe(response => { service.importFromSidecar(42).subscribe(response => {
expect(response).toEqual({message: 'done'}); expect(response).toEqual({message: 'done'});
}); });
@@ -73,6 +82,10 @@ describe('SidecarService', () => {
expect(request.request.method).toBe('POST'); expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({}); expect(request.request.body).toEqual({});
request.flush({message: 'done'}); request.flush({message: 'done'});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['books', 'detail', 42]});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookQueryKeys.collections()});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: AUTHORS_QUERY_KEY, exact: true});
}); });
it('bulk exports sidecars for a library', () => { it('bulk exports sidecars for a library', () => {
@@ -87,6 +100,8 @@ describe('SidecarService', () => {
}); });
it('bulk imports sidecars for a library', () => { it('bulk imports sidecars for a library', () => {
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue(undefined);
service.bulkImport(7).subscribe(response => { service.bulkImport(7).subscribe(response => {
expect(response).toEqual({message: 'imported', imported: 2}); expect(response).toEqual({message: 'imported', imported: 2});
}); });
@@ -95,5 +110,8 @@ describe('SidecarService', () => {
expect(request.request.method).toBe('POST'); expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({}); expect(request.request.body).toEqual({});
request.flush({message: 'imported', imported: 2}); request.flush({message: 'imported', imported: 2});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookQueryKeys.all()});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: AUTHORS_QUERY_KEY, exact: true});
}); });
}); });
@@ -1,7 +1,11 @@
import {inject, Injectable} from '@angular/core'; import {inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs'; import {Observable, tap} from 'rxjs';
import {QueryClient} from '@tanstack/angular-query-experimental';
import {API_CONFIG} from '../../../core/config/api-config'; import {API_CONFIG} from '../../../core/config/api-config';
import {invalidateAllBookCaches, invalidateBooksById} from '../../book/service/legacy-book-cache';
import {invalidateAuthorsQuery} from '../../author-browser/service/author-query-cache';
export interface SidecarCoverInfo { export interface SidecarCoverInfo {
source: string; source: string;
@@ -80,6 +84,7 @@ export type SidecarSyncStatus = 'IN_SYNC' | 'OUTDATED' | 'MISSING' | 'CONFLICT'
}) })
export class SidecarService { export class SidecarService {
private http = inject(HttpClient); private http = inject(HttpClient);
private queryClient = inject(QueryClient);
private readonly apiUrl = `${API_CONFIG.BASE_URL}/api/v1`; private readonly apiUrl = `${API_CONFIG.BASE_URL}/api/v1`;
getSidecarContent(bookId: number): Observable<SidecarMetadata> { getSidecarContent(bookId: number): Observable<SidecarMetadata> {
@@ -95,7 +100,12 @@ export class SidecarService {
} }
importFromSidecar(bookId: number): Observable<{message: string}> { importFromSidecar(bookId: number): Observable<{message: string}> {
return this.http.post<{message: string}>(`${this.apiUrl}/books/${bookId}/sidecar/import`, {}); return this.http.post<{message: string}>(`${this.apiUrl}/books/${bookId}/sidecar/import`, {}).pipe(
tap(() => {
invalidateBooksById(this.queryClient, [bookId]);
invalidateAuthorsQuery(this.queryClient);
})
);
} }
bulkExport(libraryId: number): Observable<{message: string, exported: number}> { bulkExport(libraryId: number): Observable<{message: string, exported: number}> {
@@ -107,6 +117,11 @@ export class SidecarService {
bulkImport(libraryId: number): Observable<{message: string, imported: number}> { bulkImport(libraryId: number): Observable<{message: string, imported: number}> {
return this.http.post<{message: string, imported: number}>( return this.http.post<{message: string, imported: number}>(
`${this.apiUrl}/libraries/${libraryId}/sidecar/import-all`, {} `${this.apiUrl}/libraries/${libraryId}/sidecar/import-all`, {}
).pipe(
tap(() => {
invalidateAllBookCaches(this.queryClient);
invalidateAuthorsQuery(this.queryClient);
})
); );
} }
} }
@@ -1,22 +1,28 @@
import {provideHttpClient} from '@angular/common/http'; import {provideHttpClient} from '@angular/common/http';
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {afterEach, beforeEach, describe, expect, it} from 'vitest'; import {QueryClient} from '@tanstack/angular-query-experimental';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {API_CONFIG} from '../../core/config/api-config'; import {API_CONFIG} from '../../core/config/api-config';
import {bookQueryKeys} from '../../features/book/data/book-query-keys';
import {BOOKS_QUERY_KEY} from '../../features/book/service/book-query-keys';
import {MetadataMatchWeightsService} from './metadata-match-weights.service'; import {MetadataMatchWeightsService} from './metadata-match-weights.service';
describe('MetadataMatchWeightsService', () => { describe('MetadataMatchWeightsService', () => {
let service: MetadataMatchWeightsService; let service: MetadataMatchWeightsService;
let httpTestingController: HttpTestingController; let httpTestingController: HttpTestingController;
let queryClient: QueryClient;
beforeEach(() => { beforeEach(() => {
TestBed.resetTestingModule(); TestBed.resetTestingModule();
queryClient = new QueryClient();
TestBed.configureTestingModule({ TestBed.configureTestingModule({
providers: [ providers: [
provideHttpClient(), provideHttpClient(),
provideHttpClientTesting(), provideHttpClientTesting(),
MetadataMatchWeightsService, MetadataMatchWeightsService,
{provide: QueryClient, useValue: queryClient},
] ]
}); });
@@ -26,6 +32,7 @@ describe('MetadataMatchWeightsService', () => {
afterEach(() => { afterEach(() => {
httpTestingController.verify(); httpTestingController.verify();
queryClient.clear();
TestBed.resetTestingModule(); TestBed.resetTestingModule();
}); });
@@ -41,4 +48,17 @@ describe('MetadataMatchWeightsService', () => {
request.flush(null); request.flush(null);
}); });
it('refreshes book caches once recalculated scores are saved', () => {
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue(undefined);
service.recalculateAll().subscribe();
httpTestingController.expectOne(
`${API_CONFIG.BASE_URL}/api/v1/books/metadata/recalculate-match-scores`
).flush(null);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: BOOKS_QUERY_KEY, exact: true});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookQueryKeys.all()});
});
}); });
@@ -1,15 +1,20 @@
import { inject, Injectable } from '@angular/core'; import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs'; import { Observable, tap } from 'rxjs';
import { QueryClient } from '@tanstack/angular-query-experimental';
import { API_CONFIG } from '../../core/config/api-config'; import { API_CONFIG } from '../../core/config/api-config';
import { invalidateAllBookCaches } from '../../features/book/service/legacy-book-cache';
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class MetadataMatchWeightsService { export class MetadataMatchWeightsService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1`; private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1`;
private http = inject(HttpClient); private http = inject(HttpClient);
private queryClient = inject(QueryClient);
recalculateAll(): Observable<void> { recalculateAll(): Observable<void> {
return this.http.post<void>(`${this.baseUrl}/books/metadata/recalculate-match-scores`, {}); return this.http.post<void>(`${this.baseUrl}/books/metadata/recalculate-match-scores`, {}).pipe(
tap(() => invalidateAllBookCaches(this.queryClient))
);
} }
} }