diff --git a/frontend/src/app/app.component.spec.ts b/frontend/src/app/app.component.spec.ts index ffb94e0c6..a4b73e870 100644 --- a/frontend/src/app/app.component.spec.ts +++ b/frontend/src/app/app.component.spec.ts @@ -19,6 +19,7 @@ import { ConfirmationService } from "primeng/api"; import { MessageService } from "primeng/api"; import { CommandPaletteService } from "./features/command-palette/command-palette.service"; import { LibraryImportProgressService } from "./shared/service/library-import-progress.service"; +import { AuthorService } from "./features/author-browser/service/author.service"; interface StompMessage { body: string; @@ -38,6 +39,7 @@ describe("AppComponent", () => { handleRemovedBookIds: ReturnType; handleMultipleBookUpdates: ReturnType; }; + let authorService: { handleNewlyCreatedBook: ReturnType }; let notificationEventService: { handleNewNotification: ReturnType; }; @@ -82,6 +84,7 @@ describe("AppComponent", () => { handleRemovedBookIds: vi.fn(), handleMultipleBookUpdates: vi.fn(), }; + authorService = { handleNewlyCreatedBook: vi.fn() }; notificationEventService = { handleNewNotification: vi.fn() }; metadataProgressService = { handleIncomingProgress: vi.fn() }; bookdropFileService = { handleIncomingFile: vi.fn() }; @@ -109,6 +112,7 @@ describe("AppComponent", () => { }, { provide: RxStompService, useValue: rxStompService }, { provide: BookService, useValue: bookService }, + { provide: AuthorService, useValue: authorService }, { provide: NotificationEventService, useValue: notificationEventService, @@ -168,6 +172,7 @@ describe("AppComponent", () => { ?.next({ body: JSON.stringify({ metadata: { title: "First" } }) }); expect(bookService.handleNewlyCreatedBook).toHaveBeenCalledWith({ metadata: { title: "First" } }); + expect(authorService.handleNewlyCreatedBook).toHaveBeenCalledWith({ metadata: { title: "First" } }); expect(libraryImportProgressService.recordBookAdded).toHaveBeenCalledWith("First"); }); diff --git a/frontend/src/app/app.component.ts b/frontend/src/app/app.component.ts index 9a4ca12ea..e896f5288 100644 --- a/frontend/src/app/app.component.ts +++ b/frontend/src/app/app.component.ts @@ -19,6 +19,7 @@ import {AuthService} from './shared/service/auth.service'; import {CommandPaletteComponent} from './features/command-palette/command-palette.component'; import {CommandPaletteService} from './features/command-palette/command-palette.service'; import {LibraryImportProgressService} from './shared/service/library-import-progress.service'; +import {AuthorService} from './features/author-browser/service/author.service'; @Component({ selector: 'app-root', @@ -37,6 +38,7 @@ export class AppComponent implements OnInit, OnDestroy { private appConfigService = inject(AppConfigService); // DO NOT REMOVE: Used to initialize app config on startup private authInit = inject(AuthInitializationService); private bookService = inject(BookService); + private authorService = inject(AuthorService); private rxStompService = inject(RxStompService); private notificationEventService = inject(NotificationEventService); private metadataProgressService = inject(MetadataProgressService); @@ -109,6 +111,7 @@ export class AppComponent implements OnInit, OnDestroy { const book = JSON.parse(msg.body); this.libraryImportProgressService.recordBookAdded(book.metadata?.title || this.translocoService.translate('book.unknownTitle')); this.bookService.handleNewlyCreatedBook(book); + this.authorService.handleNewlyCreatedBook(book); }) ); this.subscriptions.push( diff --git a/frontend/src/app/features/author-browser/service/author-query-cache.ts b/frontend/src/app/features/author-browser/service/author-query-cache.ts index 7e5b15171..d9ab56462 100644 --- a/frontend/src/app/features/author-browser/service/author-query-cache.ts +++ b/frontend/src/app/features/author-browser/service/author-query-cache.ts @@ -8,3 +8,7 @@ export function patchAuthorInCache(queryClient: QueryClient, authorId: number, f (current ?? []).map(author => author.id === authorId ? {...author, ...fields} : author) ); } + +export function invalidateAuthorsQuery(queryClient: QueryClient): void { + void queryClient.invalidateQueries({queryKey: AUTHORS_QUERY_KEY, exact: true}); +} diff --git a/frontend/src/app/features/author-browser/service/author.service.spec.ts b/frontend/src/app/features/author-browser/service/author.service.spec.ts index 29cff00bf..ed845091a 100644 --- a/frontend/src/app/features/author-browser/service/author.service.spec.ts +++ b/frontend/src/app/features/author-browser/service/author.service.spec.ts @@ -7,8 +7,23 @@ import {of} from 'rxjs'; import {API_CONFIG} from '../../../core/config/api-config'; 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'; +function makeBook(authors?: string[]): Book { + return { + id: 1, + libraryId: 1, + libraryName: 'Library', + metadata: { + bookId: 1, + title: 'Book 1', + authors, + }, + }; +} + describe('AuthorService', () => { const httpClient = { get: vi.fn(), @@ -66,6 +81,7 @@ describe('AuthorService', () => { }); afterEach(() => { + vi.useRealTimers(); vi.restoreAllMocks(); TestBed.resetTestingModule(); }); @@ -104,6 +120,40 @@ describe('AuthorService', () => { ); }); + it('coalesces author query invalidation when newly created books introduce authors', () => { + vi.useFakeTimers(); + + service.handleNewlyCreatedBook(makeBook(['Ada Lovelace'])); + service.handleNewlyCreatedBook(makeBook(['Grace Hopper'])); + service.handleNewlyCreatedBook(makeBook(['Katherine Johnson'])); + + expect(queryClient.invalidateQueries).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(199); + expect(queryClient.invalidateQueries).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(1); + expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: AUTHORS_QUERY_KEY, exact: true}); + expect(queryClient.invalidateQueries).toHaveBeenCalledTimes(1); + }); + + it('clears pending author invalidation when the service is destroyed', () => { + vi.useFakeTimers(); + + service.handleNewlyCreatedBook(makeBook(['Ada Lovelace'])); + TestBed.resetTestingModule(); + vi.advanceTimersByTime(200); + + expect(queryClient.invalidateQueries).not.toHaveBeenCalled(); + }); + + it('does not invalidate authors when the newly created book has no authors', () => { + service.handleNewlyCreatedBook(makeBook([])); + service.handleNewlyCreatedBook(makeBook(undefined)); + + expect(queryClient.invalidateQueries).not.toHaveBeenCalled(); + }); + it('maps SSE auto-match responses and throws on error events', () => { sseClient.stream.mockReturnValueOnce(of({type: 'message', data: '{"id":3,"name":"Grace"}'})); diff --git a/frontend/src/app/features/author-browser/service/author.service.ts b/frontend/src/app/features/author-browser/service/author.service.ts index bcd5e4e9c..1d51c9e10 100644 --- a/frontend/src/app/features/author-browser/service/author.service.ts +++ b/frontend/src/app/features/author-browser/service/author.service.ts @@ -1,14 +1,15 @@ -import {computed, effect, inject, Injectable} from '@angular/core'; +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 {SseClient} from 'ngx-sse-client'; import {API_CONFIG} from '../../../core/config/api-config'; import {AuthorSummary, AuthorDetails, AuthorSearchResult, AuthorMatchRequest, AuthorUpdateRequest, AuthorPhotoResult} from '../model/author.model'; +import {Book} from '../../book/model/book.model'; 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 {patchAuthorInCache} from './author-query-cache'; +import {invalidateAuthorsQuery, patchAuthorInCache} from './author-query-cache'; @Injectable({ providedIn: 'root' @@ -19,9 +20,12 @@ export class AuthorService { private authService = inject(AuthService); private sseClient = inject(SseClient); private queryClient = inject(QueryClient); + private destroyRef = inject(DestroyRef); private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/authors`; private readonly mediaBaseUrl = `${API_CONFIG.BASE_URL}/api/v1/media`; private readonly token = this.authService.token; + private readonly authorInvalidationDebounceMs = 200; + private authorInvalidationTimer: ReturnType | null = null; private authorsQuery = injectQuery(() => ({ ...this.getAuthorsQueryOptions(), @@ -32,6 +36,8 @@ export class AuthorService { isAuthorsLoading = computed(() => !!this.token() && this.authorsQuery.isPending()); constructor() { + this.destroyRef.onDestroy(() => this.clearAuthorInvalidationTimer()); + effect(() => { const token = this.token(); if (token === null) { @@ -48,7 +54,32 @@ export class AuthorService { } invalidateAuthors(): void { - void this.queryClient.invalidateQueries({queryKey: AUTHORS_QUERY_KEY, exact: true}); + invalidateAuthorsQuery(this.queryClient); + } + + handleNewlyCreatedBook(book: Book): void { + if (!book.metadata?.authors?.length) { + return; + } + this.debouncedInvalidateAuthors(); + } + + private debouncedInvalidateAuthors(): void { + this.clearAuthorInvalidationTimer(); + + this.authorInvalidationTimer = setTimeout(() => { + this.authorInvalidationTimer = null; + this.invalidateAuthors(); + }, this.authorInvalidationDebounceMs); + } + + private clearAuthorInvalidationTimer(): void { + if (this.authorInvalidationTimer === null) { + return; + } + + clearTimeout(this.authorInvalidationTimer); + this.authorInvalidationTimer = null; } patchAuthorInCache(authorId: number, fields: Partial): void {