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', () => {
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 {AUTHORS_QUERY_KEY} from './author-query-keys';
import {AuthorService} from './author.service';
import {bookQueryKeys} from '../../book/data/book-query-keys';
function makeBook(authors?: string[]): Book {
return {
@@ -183,6 +184,28 @@ describe('AuthorService', () => {
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', () => {
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`);
@@ -1,7 +1,7 @@
import {computed, DestroyRef, effect, inject, Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {lastValueFrom, Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {map, tap} from 'rxjs/operators';
import {SseClient} from 'ngx-sse-client';
import {API_CONFIG} from '../../../core/config/api-config';
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 {AUTHORS_QUERY_KEY} from './author-query-keys';
import {invalidateAuthorsQuery, patchAuthorInCache} from './author-query-cache';
import {invalidateAllBookCaches} from '../../book/service/legacy-book-cache';
@Injectable({
providedIn: 'root'
@@ -136,7 +137,9 @@ export class AuthorService {
}
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> {
@@ -144,7 +147,12 @@ export class AuthorService {
}
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> {
@@ -8,6 +8,7 @@ import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type'
import {Book, ReadStatus} from '../model/book.model';
import {BOOKS_QUERY_KEY} from './book-query-keys';
import {BookPatchService} from './book-patch.service';
import {shelfDefinitionQueryKeys} from '../data/shelf-definition-query-keys';
function buildBook(id: number, overrides: Partial<Book> = {}): Book {
return {
@@ -203,4 +204,14 @@ describe('BookPatchService', () => {
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,
patchBookFieldsInCache,
} from './legacy-book-cache';
import {invalidateShelfDefinitions} from '../data/shelf-definition-query-cache';
function getResetProgressFields(type: ResetProgressType): Partial<Book> {
if (type === ResetProgressTypes.KOREADER) {
@@ -105,6 +106,7 @@ export class BookPatchService {
return this.http.post<Book[]>(`${this.url}/shelves`, requestPayload).pipe(
tap(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 type {Library} from '../model/library.model';
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 {SHELVES_QUERY_KEY} from './shelf-query-keys';
import {LIBRARIES_QUERY_KEY, libraryFormatCountsQueryKey} from './library-query-keys';
import {LibraryService} from './library.service';
@@ -77,7 +81,7 @@ describe('LibraryService', () => {
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([]);
service.updateLibrary(buildLibrary({name: 'Updated'}), 4).subscribe();
@@ -85,6 +89,14 @@ describe('LibraryService', () => {
expect(updateRequest.request.method).toBe('PUT');
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();
const deleteRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries/4'));
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: 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});
});
@@ -8,8 +8,11 @@ import {Library} from '../model/library.model';
import {BookService} from './book.service';
import {API_CONFIG} from '../../../core/config/api-config';
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 {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'})
export class LibraryService {
@@ -80,7 +83,7 @@ export class LibraryService {
return this.http.put<Library>(`${this.url}/${id}`, lib).pipe(
tap(() => {
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(
tap(() => {
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});
})
);
@@ -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 type {Book} from '../model/book.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 {UserService} from '../../settings/user-management/user.service';
import {BookService} from './book.service';
@@ -127,30 +129,59 @@ describe('ShelfService', () => {
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);
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([]);
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();
const createRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves'));
expect(createRequest.request.method).toBe('POST');
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();
const updateRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves/11'));
expect(updateRequest.request.method).toBe('PUT');
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();
const deleteRequest = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves/11'));
expect(deleteRequest.request.method).toBe('DELETE');
deleteRequest.flush(null);
expect(invalidateQueriesSpy).toHaveBeenCalledTimes(4);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['shelves'], exact: true});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: shelfDefinitionQueryKeys.all()});
expect(bookService.removeBooksFromShelf).toHaveBeenCalledWith(11);
});
@@ -5,13 +5,15 @@ import {tap} from 'rxjs/operators';
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
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 {API_CONFIG} from '../../../core/config/api-config';
import {Book} from '../model/book.model';
import {UserService} from '../../settings/user-management/user.service';
import {AuthService} from '../../../shared/service/auth.service';
const SHELVES_QUERY_KEY = ['shelves'] as const;
const KOBO_SHELF_NAME = 'Kobo';
const KOBO_SHELF_ICON = 'pi pi-tablet';
@@ -67,6 +69,7 @@ export class ShelfService {
return this.http.post<Shelf>(this.url, shelf).pipe(
tap(() => {
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(
tap(() => {
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(() => {
this.bookService.removeBooksFromShelf(id);
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 {BookRuleEvaluatorService} from './book-rule-evaluator.service';
import {MagicShelfService, type MagicShelf} from './magic-shelf.service';
import {bookQueryKeys} from '../../book/data/book-query-keys';
function buildMagicShelf(overrides: Partial<MagicShelf> = {}): MagicShelf {
return {
@@ -170,6 +171,26 @@ describe('MagicShelfService', () => {
request.flush(buildMagicShelf({id: 11, name: 'Magic', filterJson: JSON.stringify(group), isPublic: 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', () => {
@@ -184,6 +205,7 @@ describe('MagicShelfService', () => {
request.flush(null);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: ['magicShelves'], exact: true});
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookQueryKeys.collections()});
});
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 {GroupRule} from '../component/magic-shelf-component';
import {IconType} from '../../../shared/icons/icon-selection';
import {invalidateBookCollections} from '../../book/data/book-query-cache';
export interface MagicShelf {
id?: number | null;
@@ -89,6 +90,9 @@ export class MagicShelfService {
return this.http.post<MagicShelf>(this.url, payload).pipe(
tap(() => {
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(
tap(() => {
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 {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/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 {bookQueryKeys} from '../../book/data/book-query-keys';
import {AUTHORS_QUERY_KEY} from '../../author-browser/service/author-query-keys';
import {SidecarService} from './sidecar.service';
describe('SidecarService', () => {
let service: SidecarService;
let httpTestingController: HttpTestingController;
let queryClient: QueryClient;
beforeEach(() => {
queryClient = new QueryClient();
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
SidecarService,
{provide: QueryClient, useValue: queryClient},
]
});
@@ -25,6 +31,7 @@ describe('SidecarService', () => {
afterEach(() => {
httpTestingController.verify();
queryClient.clear();
TestBed.resetTestingModule();
});
@@ -65,6 +72,8 @@ describe('SidecarService', () => {
});
it('imports a sidecar for a book', () => {
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue(undefined);
service.importFromSidecar(42).subscribe(response => {
expect(response).toEqual({message: 'done'});
});
@@ -73,6 +82,10 @@ describe('SidecarService', () => {
expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({});
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', () => {
@@ -87,6 +100,8 @@ describe('SidecarService', () => {
});
it('bulk imports sidecars for a library', () => {
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue(undefined);
service.bulkImport(7).subscribe(response => {
expect(response).toEqual({message: 'imported', imported: 2});
});
@@ -95,5 +110,8 @@ describe('SidecarService', () => {
expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({});
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 {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 {invalidateAllBookCaches, invalidateBooksById} from '../../book/service/legacy-book-cache';
import {invalidateAuthorsQuery} from '../../author-browser/service/author-query-cache';
export interface SidecarCoverInfo {
source: string;
@@ -80,6 +84,7 @@ export type SidecarSyncStatus = 'IN_SYNC' | 'OUTDATED' | 'MISSING' | 'CONFLICT'
})
export class SidecarService {
private http = inject(HttpClient);
private queryClient = inject(QueryClient);
private readonly apiUrl = `${API_CONFIG.BASE_URL}/api/v1`;
getSidecarContent(bookId: number): Observable<SidecarMetadata> {
@@ -95,7 +100,12 @@ export class SidecarService {
}
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}> {
@@ -107,6 +117,11 @@ export class SidecarService {
bulkImport(libraryId: number): Observable<{message: string, imported: number}> {
return this.http.post<{message: string, imported: number}>(
`${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 {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/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 {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';
describe('MetadataMatchWeightsService', () => {
let service: MetadataMatchWeightsService;
let httpTestingController: HttpTestingController;
let queryClient: QueryClient;
beforeEach(() => {
TestBed.resetTestingModule();
queryClient = new QueryClient();
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
MetadataMatchWeightsService,
{provide: QueryClient, useValue: queryClient},
]
});
@@ -26,6 +32,7 @@ describe('MetadataMatchWeightsService', () => {
afterEach(() => {
httpTestingController.verify();
queryClient.clear();
TestBed.resetTestingModule();
});
@@ -41,4 +48,17 @@ describe('MetadataMatchWeightsService', () => {
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 { 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 { invalidateAllBookCaches } from '../../features/book/service/legacy-book-cache';
@Injectable({ providedIn: 'root' })
export class MetadataMatchWeightsService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1`;
private http = inject(HttpClient);
private queryClient = inject(QueryClient);
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))
);
}
}