refactor(books): update both book caches from socket events (#2209)
This commit is contained in:
@@ -1,7 +1,8 @@
|
|||||||
import { signal } from "@angular/core";
|
import { signal } from "@angular/core";
|
||||||
import { ComponentFixture, TestBed } from "@angular/core/testing";
|
import { ComponentFixture, TestBed } from "@angular/core/testing";
|
||||||
import { TranslocoTestingModule } from "@jsverse/transloco";
|
import { TranslocoTestingModule } from "@jsverse/transloco";
|
||||||
import { Subject } from "rxjs";
|
import { BehaviorSubject, Subject } from "rxjs";
|
||||||
|
import { RxStompState } from "@stomp/rx-stomp";
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
import { AppComponent } from "./app.component";
|
import { AppComponent } from "./app.component";
|
||||||
@@ -32,15 +33,23 @@ describe("AppComponent", () => {
|
|||||||
let fixture: ComponentFixture<AppComponent>;
|
let fixture: ComponentFixture<AppComponent>;
|
||||||
let component: AppComponent;
|
let component: AppComponent;
|
||||||
let topics: Map<string, Subject<StompMessage>>;
|
let topics: Map<string, Subject<StompMessage>>;
|
||||||
let rxStompService: { watch: ReturnType<typeof vi.fn> };
|
let connectionState: BehaviorSubject<RxStompState>;
|
||||||
|
let rxStompService: {
|
||||||
|
watch: ReturnType<typeof vi.fn>;
|
||||||
|
connectionState$: BehaviorSubject<RxStompState>;
|
||||||
|
};
|
||||||
let bookService: {
|
let bookService: {
|
||||||
handleNewlyCreatedBook: ReturnType<typeof vi.fn>;
|
handleNewlyCreatedBook: ReturnType<typeof vi.fn>;
|
||||||
handleBookUpdate: ReturnType<typeof vi.fn>;
|
handleBookUpdate: ReturnType<typeof vi.fn>;
|
||||||
handleMultipleBookCoverPatches: ReturnType<typeof vi.fn>;
|
handleMultipleBookCoverPatches: ReturnType<typeof vi.fn>;
|
||||||
handleRemovedBookIds: ReturnType<typeof vi.fn>;
|
handleRemovedBookIds: ReturnType<typeof vi.fn>;
|
||||||
handleMultipleBookUpdates: ReturnType<typeof vi.fn>;
|
handleTaskProgress: ReturnType<typeof vi.fn>;
|
||||||
|
handleReconnect: ReturnType<typeof vi.fn>;
|
||||||
|
};
|
||||||
|
let authorService: {
|
||||||
|
handleNewlyCreatedBook: ReturnType<typeof vi.fn>;
|
||||||
|
invalidateAuthors: ReturnType<typeof vi.fn>;
|
||||||
};
|
};
|
||||||
let authorService: { handleNewlyCreatedBook: ReturnType<typeof vi.fn> };
|
|
||||||
let notificationEventService: {
|
let notificationEventService: {
|
||||||
handleNewNotification: ReturnType<typeof vi.fn>;
|
handleNewNotification: ReturnType<typeof vi.fn>;
|
||||||
};
|
};
|
||||||
@@ -74,19 +83,22 @@ describe("AppComponent", () => {
|
|||||||
auth = DEFAULT_AUTH
|
auth = DEFAULT_AUTH
|
||||||
): void {
|
): void {
|
||||||
topics = new Map();
|
topics = new Map();
|
||||||
|
connectionState = new BehaviorSubject<RxStompState>(RxStompState.CLOSED);
|
||||||
rxStompService = {
|
rxStompService = {
|
||||||
watch: vi.fn((topic: string) =>
|
watch: vi.fn((topic: string) =>
|
||||||
(topics.get(topic) ?? createTopicStream(topic)).asObservable(),
|
(topics.get(topic) ?? createTopicStream(topic)).asObservable(),
|
||||||
),
|
),
|
||||||
|
connectionState$: connectionState,
|
||||||
};
|
};
|
||||||
bookService = {
|
bookService = {
|
||||||
handleNewlyCreatedBook: vi.fn(),
|
handleNewlyCreatedBook: vi.fn(),
|
||||||
handleBookUpdate: vi.fn(),
|
handleBookUpdate: vi.fn(),
|
||||||
handleMultipleBookCoverPatches: vi.fn(),
|
handleMultipleBookCoverPatches: vi.fn(),
|
||||||
handleRemovedBookIds: vi.fn(),
|
handleRemovedBookIds: vi.fn(),
|
||||||
handleMultipleBookUpdates: vi.fn(),
|
handleTaskProgress: vi.fn(),
|
||||||
|
handleReconnect: vi.fn(),
|
||||||
};
|
};
|
||||||
authorService = { handleNewlyCreatedBook: vi.fn() };
|
authorService = { handleNewlyCreatedBook: vi.fn(), invalidateAuthors: vi.fn() };
|
||||||
notificationEventService = { handleNewNotification: vi.fn() };
|
notificationEventService = { handleNewNotification: vi.fn() };
|
||||||
metadataProgressService = { handleIncomingProgress: vi.fn() };
|
metadataProgressService = { handleIncomingProgress: vi.fn() };
|
||||||
bookdropFileService = { handleIncomingFile: vi.fn() };
|
bookdropFileService = { handleIncomingFile: vi.fn() };
|
||||||
@@ -185,7 +197,7 @@ describe("AppComponent", () => {
|
|||||||
|
|
||||||
topics
|
topics
|
||||||
.get("/user/queue/book-update")
|
.get("/user/queue/book-update")
|
||||||
?.next({ body: JSON.stringify({ id: 1 }) });
|
?.next({ body: JSON.stringify({ id: 1, libraryId: 1, libraryName: "Library" }) });
|
||||||
topics
|
topics
|
||||||
.get("/user/queue/books-cover-update")
|
.get("/user/queue/books-cover-update")
|
||||||
?.next({ body: JSON.stringify([{ id: 1 }]) });
|
?.next({ body: JSON.stringify([{ id: 1 }]) });
|
||||||
@@ -194,10 +206,7 @@ describe("AppComponent", () => {
|
|||||||
?.next({ body: JSON.stringify([1, 2]) });
|
?.next({ body: JSON.stringify([1, 2]) });
|
||||||
topics
|
topics
|
||||||
.get("/user/queue/book-metadata-update")
|
.get("/user/queue/book-metadata-update")
|
||||||
?.next({ body: JSON.stringify({ id: 2 }) });
|
?.next({ body: JSON.stringify({ id: 2, libraryId: 1, libraryName: "Library" }) });
|
||||||
topics
|
|
||||||
.get("/user/queue/book-metadata-batch-update")
|
|
||||||
?.next({ body: JSON.stringify([{ id: 3 }]) });
|
|
||||||
topics
|
topics
|
||||||
.get("/user/queue/book-metadata-batch-progress")
|
.get("/user/queue/book-metadata-batch-progress")
|
||||||
?.next({ body: JSON.stringify({ taskId: "task-1" }) });
|
?.next({ body: JSON.stringify({ taskId: "task-1" }) });
|
||||||
@@ -211,12 +220,15 @@ describe("AppComponent", () => {
|
|||||||
.get("/user/queue/task-progress")
|
.get("/user/queue/task-progress")
|
||||||
?.next({ body: JSON.stringify({ taskId: "task-2" }) });
|
?.next({ body: JSON.stringify({ taskId: "task-2" }) });
|
||||||
|
|
||||||
expect(bookService.handleBookUpdate).toHaveBeenCalledWith({ id: 1 });
|
expect(bookService.handleBookUpdate).toHaveBeenCalledWith(
|
||||||
|
{ id: 1, libraryId: 1, libraryName: "Library" },
|
||||||
|
);
|
||||||
|
expect(bookService.handleBookUpdate).toHaveBeenCalledWith(
|
||||||
|
{ id: 2, libraryId: 1, libraryName: "Library" },
|
||||||
|
);
|
||||||
expect(bookService.handleMultipleBookCoverPatches).toHaveBeenCalledWith([
|
expect(bookService.handleMultipleBookCoverPatches).toHaveBeenCalledWith([
|
||||||
{ id: 1 }]);
|
{ id: 1 }]);
|
||||||
expect(bookService.handleRemovedBookIds).toHaveBeenCalledWith([1, 2]);
|
expect(bookService.handleRemovedBookIds).toHaveBeenCalledWith([1, 2]);
|
||||||
expect(bookService.handleMultipleBookUpdates).toHaveBeenCalledWith([
|
|
||||||
{ id: 3 }]);
|
|
||||||
expect(metadataProgressService.handleIncomingProgress).toHaveBeenCalledWith(
|
expect(metadataProgressService.handleIncomingProgress).toHaveBeenCalledWith(
|
||||||
{ taskId: "task-1" },
|
{ taskId: "task-1" },
|
||||||
);
|
);
|
||||||
@@ -236,6 +248,22 @@ describe("AppComponent", () => {
|
|||||||
expect(taskService.handleTaskProgress).toHaveBeenCalledWith({
|
expect(taskService.handleTaskProgress).toHaveBeenCalledWith({
|
||||||
taskId: "task-2",
|
taskId: "task-2",
|
||||||
});
|
});
|
||||||
|
expect(bookService.handleTaskProgress).toHaveBeenCalledWith({
|
||||||
|
taskId: "task-2",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reconciles book caches after a websocket reconnect", () => {
|
||||||
|
configureComponent();
|
||||||
|
|
||||||
|
connectionState.next(RxStompState.OPEN);
|
||||||
|
expect(bookService.handleReconnect).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
connectionState.next(RxStompState.CLOSED);
|
||||||
|
connectionState.next(RxStompState.OPEN);
|
||||||
|
|
||||||
|
expect(bookService.handleReconnect).toHaveBeenCalledOnce();
|
||||||
|
expect(authorService.invalidateAuthors).toHaveBeenCalledOnce();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("forces logout when the session is revoked", () => {
|
it("forces logout when the session is revoked", () => {
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import {CommandPaletteService} from './features/command-palette/command-palette.
|
|||||||
import {LibraryImportProgressService} from './shared/service/library-import-progress.service';
|
import {LibraryImportProgressService} from './shared/service/library-import-progress.service';
|
||||||
import {AuthorService} from './features/author-browser/service/author.service';
|
import {AuthorService} from './features/author-browser/service/author.service';
|
||||||
import {MetadataRefreshSubmissionService} from './features/metadata/data/metadata-refresh-submission.service';
|
import {MetadataRefreshSubmissionService} from './features/metadata/data/metadata-refresh-submission.service';
|
||||||
|
import {RxStompState} from '@stomp/rx-stomp';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-root',
|
selector: 'app-root',
|
||||||
@@ -108,6 +109,20 @@ export class AppComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private setupWebSocketSubscriptions(): void {
|
private setupWebSocketSubscriptions(): void {
|
||||||
|
let hasConnected = false;
|
||||||
|
this.subscriptions.push(
|
||||||
|
this.rxStompService.connectionState$.subscribe(state => {
|
||||||
|
if (state !== RxStompState.OPEN) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (hasConnected) {
|
||||||
|
this.bookService.handleReconnect();
|
||||||
|
this.authorService.invalidateAuthors();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
hasConnected = true;
|
||||||
|
})
|
||||||
|
);
|
||||||
this.subscriptions.push(
|
this.subscriptions.push(
|
||||||
this.rxStompService.watch('/user/queue/book-add').subscribe(msg => {
|
this.rxStompService.watch('/user/queue/book-add').subscribe(msg => {
|
||||||
const book = JSON.parse(msg.body);
|
const book = JSON.parse(msg.body);
|
||||||
@@ -136,11 +151,6 @@ export class AppComponent implements OnInit, OnDestroy {
|
|||||||
this.bookService.handleBookUpdate(JSON.parse(msg.body))
|
this.bookService.handleBookUpdate(JSON.parse(msg.body))
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
this.subscriptions.push(
|
|
||||||
this.rxStompService.watch('/user/queue/book-metadata-batch-update').subscribe(msg =>
|
|
||||||
this.bookService.handleMultipleBookUpdates(JSON.parse(msg.body))
|
|
||||||
)
|
|
||||||
);
|
|
||||||
this.subscriptions.push(
|
this.subscriptions.push(
|
||||||
this.rxStompService.watch('/user/queue/book-metadata-batch-progress').subscribe(msg => {
|
this.rxStompService.watch('/user/queue/book-metadata-batch-progress').subscribe(msg => {
|
||||||
const progress = JSON.parse(msg.body) as MetadataBatchProgressNotification;
|
const progress = JSON.parse(msg.body) as MetadataBatchProgressNotification;
|
||||||
@@ -164,6 +174,7 @@ export class AppComponent implements OnInit, OnDestroy {
|
|||||||
this.rxStompService.watch('/user/queue/task-progress').subscribe(msg => {
|
this.rxStompService.watch('/user/queue/task-progress').subscribe(msg => {
|
||||||
const progress = JSON.parse(msg.body) as TaskProgressPayload;
|
const progress = JSON.parse(msg.body) as TaskProgressPayload;
|
||||||
this.taskService.handleTaskProgress(progress);
|
this.taskService.handleTaskProgress(progress);
|
||||||
|
this.bookService.handleTaskProgress(progress);
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
this.subscriptions.push(
|
this.subscriptions.push(
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import {ApplicationRef, provideZonelessChangeDetection, signal, type Environment
|
|||||||
import {provideHttpClient} from '@angular/common/http';
|
import {provideHttpClient} from '@angular/common/http';
|
||||||
import {provideHttpClientTesting} from '@angular/common/http/testing';
|
import {provideHttpClientTesting} from '@angular/common/http/testing';
|
||||||
import {TestBed} from '@angular/core/testing';
|
import {TestBed} from '@angular/core/testing';
|
||||||
import {provideTanStackQuery, QueryClient} from '@tanstack/angular-query-experimental';
|
import {provideTanStackQuery, QueryClient, QueryObserver} from '@tanstack/angular-query-experimental';
|
||||||
|
|
||||||
interface AuthServiceStub {
|
interface AuthServiceStub {
|
||||||
token: WritableSignal<string | null>;
|
token: WritableSignal<string | null>;
|
||||||
@@ -40,6 +40,35 @@ export function flushSignalAndQueryEffects(): void {
|
|||||||
TestBed.flushEffects();
|
TestBed.flushEffects();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function observeActiveQuery(queryClient: QueryClient, queryKey: readonly unknown[], data: unknown) {
|
||||||
|
let fetchCount = 0;
|
||||||
|
let abortCount = 0;
|
||||||
|
const pendingResolutions: (() => void)[] = [];
|
||||||
|
|
||||||
|
queryClient.setQueryData(queryKey, data);
|
||||||
|
const observer = new QueryObserver(queryClient, {
|
||||||
|
queryKey,
|
||||||
|
staleTime: Infinity,
|
||||||
|
queryFn: ({signal}) => new Promise(resolve => {
|
||||||
|
fetchCount += 1;
|
||||||
|
signal.addEventListener('abort', () => {
|
||||||
|
abortCount += 1;
|
||||||
|
});
|
||||||
|
pendingResolutions.push(() => resolve(data));
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const unsubscribe = observer.subscribe(() => undefined);
|
||||||
|
|
||||||
|
return {
|
||||||
|
fetchCount: () => fetchCount,
|
||||||
|
abortCount: () => abortCount,
|
||||||
|
finish: () => {
|
||||||
|
pendingResolutions.splice(0).forEach(resolve => resolve());
|
||||||
|
unsubscribe();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Asynchronously flushes Angular effects and query state across multiple rounds.
|
* Asynchronously flushes Angular effects and query state across multiple rounds.
|
||||||
* Use this for tests involving async operations like HTTP requests or timers.
|
* Use this for tests involving async operations like HTTP requests or timers.
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import {QueryClient, QueryObserver} from '@tanstack/angular-query-experimental';
|
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
|
||||||
|
import {observeActiveQuery} from '../../../core/testing/query-testing';
|
||||||
import {
|
import {
|
||||||
invalidateAllBookQueries,
|
invalidateAllBookQueries,
|
||||||
invalidateBookCollections,
|
invalidateBookCollections,
|
||||||
@@ -30,35 +31,6 @@ function seedAllQueryFamilies(queryClient: QueryClient): void {
|
|||||||
queryClient.setQueryData(secondRecommendationKey, [firstBook]);
|
queryClient.setQueryData(secondRecommendationKey, [firstBook]);
|
||||||
}
|
}
|
||||||
|
|
||||||
function observeActiveQuery(queryClient: QueryClient, queryKey: readonly unknown[], data: unknown) {
|
|
||||||
let fetchCount = 0;
|
|
||||||
let abortCount = 0;
|
|
||||||
const pendingResolutions: (() => void)[] = [];
|
|
||||||
|
|
||||||
queryClient.setQueryData(queryKey, data);
|
|
||||||
const observer = new QueryObserver(queryClient, {
|
|
||||||
queryKey,
|
|
||||||
staleTime: Infinity,
|
|
||||||
queryFn: ({signal}) => new Promise(resolve => {
|
|
||||||
fetchCount += 1;
|
|
||||||
signal.addEventListener('abort', () => {
|
|
||||||
abortCount += 1;
|
|
||||||
});
|
|
||||||
pendingResolutions.push(() => resolve(data));
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
const unsubscribe = observer.subscribe(() => undefined);
|
|
||||||
|
|
||||||
return {
|
|
||||||
fetchCount: () => fetchCount,
|
|
||||||
abortCount: () => abortCount,
|
|
||||||
finish: () => {
|
|
||||||
pendingResolutions.splice(0).forEach(resolve => resolve());
|
|
||||||
unsubscribe();
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('book query cache', () => {
|
describe('book query cache', () => {
|
||||||
let queryClient: QueryClient;
|
let queryClient: QueryClient;
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
export const BOOKS_QUERY_KEY = ['books'] as const;
|
export const BOOKS_QUERY_KEY = ['books'] as const;
|
||||||
|
|
||||||
|
export const BOOK_DETAIL_QUERY_PREFIX = ['books', 'detail'] as const;
|
||||||
|
|
||||||
|
export const BOOK_RECOMMENDATIONS_QUERY_PREFIX = ['books', 'recommendations'] as const;
|
||||||
|
|
||||||
export const bookDetailQueryKey = (bookId: number, withDescription: boolean) =>
|
export const bookDetailQueryKey = (bookId: number, withDescription: boolean) =>
|
||||||
['books', 'detail', bookId, withDescription] as const;
|
[...BOOK_DETAIL_QUERY_PREFIX, bookId, withDescription] as const;
|
||||||
|
|
||||||
export const bookDetailQueryPrefix = (bookId: number) =>
|
export const bookDetailQueryPrefix = (bookId: number) =>
|
||||||
['books', 'detail', bookId] as const;
|
[...BOOK_DETAIL_QUERY_PREFIX, bookId] as const;
|
||||||
|
|
||||||
export const bookRecommendationsQueryKey = (bookId: number, limit: number) =>
|
export const bookRecommendationsQueryKey = (bookId: number, limit: number) =>
|
||||||
['books', 'recommendations', bookId, limit] as const;
|
[...BOOK_RECOMMENDATIONS_QUERY_PREFIX, bookId, limit] as const;
|
||||||
|
|
||||||
export const bookRecommendationsQueryPrefix = (bookId: number) =>
|
export const bookRecommendationsQueryPrefix = (bookId: number) =>
|
||||||
['books', 'recommendations', bookId] as const;
|
[...BOOK_RECOMMENDATIONS_QUERY_PREFIX, bookId] as const;
|
||||||
|
|||||||
@@ -2,10 +2,22 @@ import {TestBed} from '@angular/core/testing';
|
|||||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
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 {observeActiveQuery} from '../../../core/testing/query-testing';
|
||||||
import {Book} from '../model/book.model';
|
import {Book} from '../model/book.model';
|
||||||
|
import {TaskStatus} from '../../settings/task-management/task.service';
|
||||||
|
import {bookQueryKeys} from '../data/book-query-keys';
|
||||||
|
import {BookDetail} from '../data/book-response.models';
|
||||||
|
import {normalizeBookPageParams} from '../data/book-query-params';
|
||||||
import {BOOKS_QUERY_KEY, bookDetailQueryKey, bookRecommendationsQueryKey} from './book-query-keys';
|
import {BOOKS_QUERY_KEY, bookDetailQueryKey, bookRecommendationsQueryKey} from './book-query-keys';
|
||||||
import {BookSocketService} from './book-socket.service';
|
import {BookSocketService} from './book-socket.service';
|
||||||
|
|
||||||
|
const PAGE_QUERY_KEY = bookQueryKeys.boundedPage(normalizeBookPageParams({
|
||||||
|
size: 20,
|
||||||
|
facets: {},
|
||||||
|
facetLogic: 'or',
|
||||||
|
sort: [],
|
||||||
|
}));
|
||||||
|
|
||||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
@@ -25,6 +37,7 @@ describe('BookSocketService', () => {
|
|||||||
let queryClient: QueryClient;
|
let queryClient: QueryClient;
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers();
|
||||||
queryClient = new QueryClient();
|
queryClient = new QueryClient();
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
@@ -41,73 +54,167 @@ describe('BookSocketService', () => {
|
|||||||
queryClient.clear();
|
queryClient.clear();
|
||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
vi.restoreAllMocks();
|
vi.restoreAllMocks();
|
||||||
|
vi.useRealTimers();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('adds newly created books into the list cache', () => {
|
function flushSocketChanges(): void {
|
||||||
|
vi.advanceTimersToNextTimer();
|
||||||
|
}
|
||||||
|
|
||||||
|
function isInvalidated(queryKey: readonly unknown[]): boolean | undefined {
|
||||||
|
return queryClient.getQueryState(queryKey)?.isInvalidated;
|
||||||
|
}
|
||||||
|
|
||||||
|
it('upserts a newly created book without refetching the legacy list', () => {
|
||||||
const existing = makeBook(1);
|
const existing = makeBook(1);
|
||||||
const created = makeBook(2);
|
const created = makeBook(2);
|
||||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [existing]);
|
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [existing]);
|
||||||
|
queryClient.setQueryData(PAGE_QUERY_KEY, {content: [existing]});
|
||||||
|
queryClient.setQueryData(bookQueryKeys.detail(2, false), {id: 2});
|
||||||
|
|
||||||
service.handleNewlyCreatedBook(created);
|
service.handleNewlyCreatedBook(created);
|
||||||
|
|
||||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([existing, created]);
|
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([existing, created]);
|
||||||
|
expect(isInvalidated(BOOKS_QUERY_KEY)).toBe(false);
|
||||||
|
expect(isInvalidated(PAGE_QUERY_KEY)).toBe(true);
|
||||||
|
expect(isInvalidated(bookQueryKeys.detail(2, false))).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('invalidates the books query and removes detail queries for removed ids', () => {
|
it('does not manufacture a legacy list when none is cached', () => {
|
||||||
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
service.handleNewlyCreatedBook(makeBook(2));
|
||||||
const kept = makeBook(2);
|
|
||||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [makeBook(1), kept]);
|
|
||||||
queryClient.setQueryData(bookDetailQueryKey(1, false), makeBook(1));
|
|
||||||
queryClient.setQueryData(bookRecommendationsQueryKey(1, 20), [kept]);
|
|
||||||
|
|
||||||
service.handleRemovedBookIds([1]);
|
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toBeUndefined();
|
||||||
|
|
||||||
expect(invalidateSpy).toHaveBeenCalledWith({queryKey: BOOKS_QUERY_KEY, exact: true});
|
|
||||||
expect(queryClient.getQueryData(bookDetailQueryKey(1, false))).toBeUndefined();
|
|
||||||
expect(queryClient.getQueryData(bookRecommendationsQueryKey(1, 20))).toBeUndefined();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('patches updated books directly into the list cache', () => {
|
it('patches an updated book into the legacy list without touching clean query data', () => {
|
||||||
const original = makeBook(7, {libraryName: 'Original'});
|
const original = makeBook(7, {libraryName: 'Original'});
|
||||||
const updated = makeBook(7, {libraryName: 'Updated'});
|
const updated = makeBook(7, {libraryName: 'Updated'});
|
||||||
|
const cleanDetail: BookDetail = {
|
||||||
|
id: 7,
|
||||||
|
libraryId: 1,
|
||||||
|
libraryName: 'Clean library',
|
||||||
|
metadata: {bookId: 7, title: 'Clean detail'},
|
||||||
|
};
|
||||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [original]);
|
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [original]);
|
||||||
|
queryClient.setQueryData(bookQueryKeys.detail(7, false), cleanDetail);
|
||||||
|
|
||||||
service.handleBookUpdate(updated);
|
service.handleBookUpdate(updated);
|
||||||
|
|
||||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([updated]);
|
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([updated]);
|
||||||
|
expect(isInvalidated(BOOKS_QUERY_KEY)).toBe(false);
|
||||||
|
expect(queryClient.getQueryData(bookQueryKeys.detail(7, false))).toBe(cleanDetail);
|
||||||
|
expect(isInvalidated(bookQueryKeys.detail(7, false))).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('patches multiple cover timestamps and invalidates their detail queries', () => {
|
it('accepts the watcher ID-array update shape and invalidates instead of caching it as a book', () => {
|
||||||
|
const original = makeBook(8);
|
||||||
|
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [original]);
|
||||||
|
queryClient.setQueryData(bookDetailQueryKey(8, false), original);
|
||||||
|
|
||||||
|
service.handleBookUpdate([8]);
|
||||||
|
flushSocketChanges();
|
||||||
|
|
||||||
|
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([original]);
|
||||||
|
expect(isInvalidated(BOOKS_QUERY_KEY)).toBe(true);
|
||||||
|
expect(isInvalidated(bookDetailQueryKey(8, false))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('patches cover timestamps into the legacy list and invalidates the affected detail', () => {
|
||||||
const first = makeBook(3);
|
const first = makeBook(3);
|
||||||
const second = makeBook(4, {
|
const second = makeBook(4);
|
||||||
metadata: {
|
|
||||||
bookId: 4,
|
|
||||||
title: 'Book 4',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
|
||||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [first, second]);
|
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [first, second]);
|
||||||
|
queryClient.setQueryData(bookDetailQueryKey(3, false), first);
|
||||||
|
|
||||||
service.handleMultipleBookCoverPatches([{id: 3, coverUpdatedOn: '2026-03-26T12:34:00Z'}]);
|
service.handleMultipleBookCoverPatches([{id: 3, coverUpdatedOn: '2026-03-26T12:34:00Z'}]);
|
||||||
|
|
||||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([
|
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([
|
||||||
{
|
{...first, metadata: {...first.metadata, coverUpdatedOn: '2026-03-26T12:34:00Z'}},
|
||||||
...first,
|
|
||||||
metadata: {
|
|
||||||
...first.metadata,
|
|
||||||
coverUpdatedOn: '2026-03-26T12:34:00Z',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
second,
|
second,
|
||||||
]);
|
]);
|
||||||
expect(invalidateSpy).toHaveBeenCalledWith({queryKey: ['books', 'detail', 3]});
|
expect(isInvalidated(BOOKS_QUERY_KEY)).toBe(false);
|
||||||
|
expect(isInvalidated(bookDetailQueryKey(3, false))).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('ignores empty cover patch lists', () => {
|
it('coalesces socket bursts and lets deletion win over changes for the same book', async () => {
|
||||||
const setQueryDataSpy = vi.spyOn(queryClient, 'setQueryData');
|
const legacyBooks = observeActiveQuery(queryClient, BOOKS_QUERY_KEY, [makeBook(7), makeBook(8)]);
|
||||||
|
const modernPage = observeActiveQuery(
|
||||||
|
queryClient,
|
||||||
|
PAGE_QUERY_KEY,
|
||||||
|
{content: [makeBook(7), makeBook(8)]},
|
||||||
|
);
|
||||||
|
const changedDetail = observeActiveQuery(
|
||||||
|
queryClient,
|
||||||
|
bookQueryKeys.detail(8, false),
|
||||||
|
{id: 8},
|
||||||
|
);
|
||||||
|
const deletedDetailKey = bookQueryKeys.detail(7, false);
|
||||||
|
queryClient.setQueryData(deletedDetailKey, {id: 7});
|
||||||
|
|
||||||
service.handleMultipleBookCoverPatches([]);
|
for (let index = 0; index < 100; index += 1) {
|
||||||
|
service.handleBookUpdate([7]);
|
||||||
|
}
|
||||||
|
service.handleRemovedBookIds([7]);
|
||||||
|
service.handleBookUpdate([7]);
|
||||||
|
service.handleBookUpdate([8]);
|
||||||
|
|
||||||
expect(setQueryDataSpy).not.toHaveBeenCalled();
|
expect(legacyBooks.fetchCount()).toBe(0);
|
||||||
|
expect(modernPage.fetchCount()).toBe(0);
|
||||||
|
flushSocketChanges();
|
||||||
|
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(legacyBooks.fetchCount()).toBe(1);
|
||||||
|
expect(modernPage.fetchCount()).toBe(1);
|
||||||
|
expect(changedDetail.fetchCount()).toBe(1);
|
||||||
|
});
|
||||||
|
expect(legacyBooks.abortCount()).toBe(0);
|
||||||
|
expect(modernPage.abortCount()).toBe(0);
|
||||||
|
expect(changedDetail.abortCount()).toBe(0);
|
||||||
|
expect(queryClient.getQueryData(deletedDetailKey)).toBeUndefined();
|
||||||
|
|
||||||
|
legacyBooks.finish();
|
||||||
|
modernPage.finish();
|
||||||
|
changedDetail.finish();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates recommendations when recommendation refresh completes', () => {
|
||||||
|
queryClient.setQueryData(bookQueryKeys.recommendation(1, 20), [makeBook(2)]);
|
||||||
|
queryClient.setQueryData(bookRecommendationsQueryKey(1, 20), [makeBook(2)]);
|
||||||
|
|
||||||
|
service.handleTaskProgress({
|
||||||
|
taskId: 'task-1',
|
||||||
|
taskType: 'UPDATE_BOOK_RECOMMENDATIONS',
|
||||||
|
taskStatus: TaskStatus.COMPLETED,
|
||||||
|
progress: 100,
|
||||||
|
message: 'Done',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(isInvalidated(bookQueryKeys.recommendation(1, 20))).toBe(true);
|
||||||
|
expect(isInvalidated(bookRecommendationsQueryKey(1, 20))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{taskId: 'task-1', taskType: 'UPDATE_BOOK_RECOMMENDATIONS', taskStatus: TaskStatus.IN_PROGRESS, progress: 50, message: 'Working'},
|
||||||
|
{taskId: 'task-1', taskType: 'REFRESH_LIBRARY_METADATA', taskStatus: TaskStatus.COMPLETED, progress: 100, message: 'Done'},
|
||||||
|
])('does not reconcile books for an irrelevant task event', payload => {
|
||||||
|
queryClient.setQueryData(bookRecommendationsQueryKey(1, 20), [makeBook(2)]);
|
||||||
|
|
||||||
|
service.handleTaskProgress(payload);
|
||||||
|
|
||||||
|
expect(isInvalidated(bookRecommendationsQueryKey(1, 20))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('broadly invalidates clean and legacy book caches after reconnect', () => {
|
||||||
|
const book = makeBook(1);
|
||||||
|
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [book]);
|
||||||
|
queryClient.setQueryData(bookDetailQueryKey(1, false), book);
|
||||||
|
queryClient.setQueryData(bookRecommendationsQueryKey(1, 20), [book]);
|
||||||
|
queryClient.setQueryData(bookQueryKeys.detail(1, false), book);
|
||||||
|
|
||||||
|
service.handleReconnect();
|
||||||
|
|
||||||
|
expect(isInvalidated(BOOKS_QUERY_KEY)).toBe(true);
|
||||||
|
expect(isInvalidated(bookDetailQueryKey(1, false))).toBe(true);
|
||||||
|
expect(isInvalidated(bookRecommendationsQueryKey(1, 20))).toBe(true);
|
||||||
|
expect(isInvalidated(bookQueryKeys.detail(1, false))).toBe(true);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,56 +1,119 @@
|
|||||||
import {inject, Injectable} from '@angular/core';
|
import {DestroyRef, inject, Injectable} from '@angular/core';
|
||||||
import {Book} from '../model/book.model';
|
|
||||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||||
import {BOOKS_QUERY_KEY} from './book-query-keys';
|
|
||||||
import {
|
|
||||||
addBookToCache,
|
|
||||||
invalidateBookDetailQueries,
|
|
||||||
invalidateBooksQuery,
|
|
||||||
patchAppBooksCoverInCache,
|
|
||||||
patchBooksInCache,
|
|
||||||
removeBookQueries,
|
|
||||||
} from './book-query-cache';
|
|
||||||
|
|
||||||
@Injectable({
|
import {invalidateBookRecommendations} from '../data/book-query-cache';
|
||||||
providedIn: 'root',
|
import {TaskProgressPayload} from '../../settings/task-management/task.service';
|
||||||
})
|
import {Book} from '../model/book.model';
|
||||||
|
import {
|
||||||
|
BookCoverPatch,
|
||||||
|
invalidateAllBookCaches,
|
||||||
|
invalidateLegacyBookRecommendations,
|
||||||
|
patchBooksInCache,
|
||||||
|
patchBookCoversInCache,
|
||||||
|
reconcileBookCacheChangeSet,
|
||||||
|
upsertBooksInCache,
|
||||||
|
} from './legacy-book-cache';
|
||||||
|
|
||||||
|
function isBookIdArray(payload: Book | readonly number[]): payload is readonly number[] {
|
||||||
|
return Array.isArray(payload);
|
||||||
|
}
|
||||||
|
@Injectable({providedIn: 'root'})
|
||||||
export class BookSocketService {
|
export class BookSocketService {
|
||||||
private queryClient = inject(QueryClient);
|
private readonly queryClient = inject(QueryClient);
|
||||||
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
|
private readonly reconciliationDelayMs = 50;
|
||||||
|
private readonly pendingChangedBookIds = new Set<number>();
|
||||||
|
private readonly pendingDeletedBookIds = new Set<number>();
|
||||||
|
private reconciliationTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.destroyRef.onDestroy(() => this.clearPendingReconciliation());
|
||||||
|
}
|
||||||
|
|
||||||
handleNewlyCreatedBook(book: Book): void {
|
handleNewlyCreatedBook(book: Book): void {
|
||||||
addBookToCache(this.queryClient, book);
|
upsertBooksInCache(this.queryClient, [book]);
|
||||||
}
|
}
|
||||||
|
|
||||||
handleRemovedBookIds(removedBookIds: number[]): void {
|
handleRemovedBookIds(bookIds: readonly number[]): void {
|
||||||
invalidateBooksQuery(this.queryClient);
|
this.queueDeletedBooks(bookIds);
|
||||||
removeBookQueries(this.queryClient, removedBookIds);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
handleBookUpdate(updatedBook: Book): void {
|
handleBookUpdate(payload: Book | readonly number[]): void {
|
||||||
patchBooksInCache(this.queryClient, [updatedBook]);
|
if (isBookIdArray(payload)) {
|
||||||
}
|
this.queueKnownChanges(payload);
|
||||||
|
return;
|
||||||
handleMultipleBookUpdates(updatedBooks: Book[]): void {
|
}
|
||||||
patchBooksInCache(this.queryClient, updatedBooks);
|
patchBooksInCache(this.queryClient, [payload]);
|
||||||
}
|
}
|
||||||
|
|
||||||
handleBookMetadataUpdate(bookId: number): void {
|
handleBookMetadataUpdate(bookId: number): void {
|
||||||
invalidateBooksQuery(this.queryClient);
|
this.queueKnownChanges([bookId]);
|
||||||
invalidateBookDetailQueries(this.queryClient, [bookId]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void {
|
handleMultipleBookCoverPatches(patches: readonly BookCoverPatch[]): void {
|
||||||
if (!patches || patches.length === 0) return;
|
patchBookCoversInCache(this.queryClient, patches);
|
||||||
const patchMap = new Map(patches.map(p => [p.id, p.coverUpdatedOn]));
|
}
|
||||||
this.queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
|
||||||
(current ?? []).map(book => {
|
handleTaskProgress(payload: TaskProgressPayload): void {
|
||||||
const coverUpdatedOn = patchMap.get(book.id);
|
if (payload.taskType !== 'UPDATE_BOOK_RECOMMENDATIONS' || payload.taskStatus !== 'COMPLETED') {
|
||||||
return coverUpdatedOn && book.metadata
|
return;
|
||||||
? {...book, metadata: {...book.metadata, coverUpdatedOn}}
|
}
|
||||||
: book;
|
void Promise.all([
|
||||||
})
|
invalidateBookRecommendations(this.queryClient),
|
||||||
|
invalidateLegacyBookRecommendations(this.queryClient),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
handleReconnect(): void {
|
||||||
|
this.clearPendingReconciliation();
|
||||||
|
invalidateAllBookCaches(this.queryClient);
|
||||||
|
}
|
||||||
|
|
||||||
|
private queueKnownChanges(bookIds: readonly number[]): void {
|
||||||
|
for (const bookId of bookIds) {
|
||||||
|
if (!this.pendingDeletedBookIds.has(bookId)) {
|
||||||
|
this.pendingChangedBookIds.add(bookId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.scheduleReconciliation();
|
||||||
|
}
|
||||||
|
|
||||||
|
private queueDeletedBooks(bookIds: readonly number[]): void {
|
||||||
|
for (const bookId of bookIds) {
|
||||||
|
this.pendingChangedBookIds.delete(bookId);
|
||||||
|
this.pendingDeletedBookIds.add(bookId);
|
||||||
|
}
|
||||||
|
this.scheduleReconciliation();
|
||||||
|
}
|
||||||
|
|
||||||
|
private scheduleReconciliation(): void {
|
||||||
|
if (this.reconciliationTimer !== null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.reconciliationTimer = setTimeout(() => this.flushPendingReconciliation(), this.reconciliationDelayMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
private flushPendingReconciliation(): void {
|
||||||
|
this.reconciliationTimer = null;
|
||||||
|
const changedBookIds = [...this.pendingChangedBookIds];
|
||||||
|
const deletedBookIds = [...this.pendingDeletedBookIds];
|
||||||
|
this.pendingChangedBookIds.clear();
|
||||||
|
this.pendingDeletedBookIds.clear();
|
||||||
|
|
||||||
|
void reconcileBookCacheChangeSet(
|
||||||
|
this.queryClient,
|
||||||
|
{changedBookIds, deletedBookIds},
|
||||||
|
{legacyList: 'needs-refetch'},
|
||||||
);
|
);
|
||||||
patchAppBooksCoverInCache(this.queryClient, patches);
|
}
|
||||||
invalidateBookDetailQueries(this.queryClient, patches.map(p => p.id));
|
|
||||||
|
private clearPendingReconciliation(): void {
|
||||||
|
if (this.reconciliationTimer !== null) {
|
||||||
|
clearTimeout(this.reconciliationTimer);
|
||||||
|
this.reconciliationTimer = null;
|
||||||
|
}
|
||||||
|
this.pendingChangedBookIds.clear();
|
||||||
|
this.pendingDeletedBookIds.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -77,9 +77,10 @@ describe('BookService', () => {
|
|||||||
handleNewlyCreatedBook: vi.fn(),
|
handleNewlyCreatedBook: vi.fn(),
|
||||||
handleRemovedBookIds: vi.fn(),
|
handleRemovedBookIds: vi.fn(),
|
||||||
handleBookUpdate: vi.fn(),
|
handleBookUpdate: vi.fn(),
|
||||||
handleMultipleBookUpdates: vi.fn(),
|
|
||||||
handleBookMetadataUpdate: vi.fn(),
|
handleBookMetadataUpdate: vi.fn(),
|
||||||
handleMultipleBookCoverPatches: vi.fn(),
|
handleMultipleBookCoverPatches: vi.fn(),
|
||||||
|
handleTaskProgress: vi.fn(),
|
||||||
|
handleReconnect: vi.fn(),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ import {API_CONFIG} from '../../../core/config/api-config';
|
|||||||
import {MessageService} from '@openng/optimus-ui/api';
|
import {MessageService} from '@openng/optimus-ui/api';
|
||||||
import {ResetProgressType} from '../../../shared/constants/reset-progress-type';
|
import {ResetProgressType} from '../../../shared/constants/reset-progress-type';
|
||||||
import {AuthService} from '../../../shared/service/auth.service';
|
import {AuthService} from '../../../shared/service/auth.service';
|
||||||
|
import {TaskProgressPayload} from '../../settings/task-management/task.service';
|
||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
import {BookSocketService} from './book-socket.service';
|
import {BookSocketService} from './book-socket.service';
|
||||||
|
import type {BookCoverPatch} from './legacy-book-cache';
|
||||||
import {BookPatchService} from './book-patch.service';
|
import {BookPatchService} from './book-patch.service';
|
||||||
import {TranslocoService} from '@jsverse/transloco';
|
import {TranslocoService} from '@jsverse/transloco';
|
||||||
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
|
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
|
||||||
@@ -377,19 +379,23 @@ export class BookService {
|
|||||||
this.bookSocketService.handleRemovedBookIds(removedBookIds);
|
this.bookSocketService.handleRemovedBookIds(removedBookIds);
|
||||||
}
|
}
|
||||||
|
|
||||||
handleBookUpdate(updatedBook: Book): void {
|
handleBookUpdate(payload: Book | readonly number[]): void {
|
||||||
this.bookSocketService.handleBookUpdate(updatedBook);
|
this.bookSocketService.handleBookUpdate(payload);
|
||||||
}
|
|
||||||
|
|
||||||
handleMultipleBookUpdates(updatedBooks: Book[]): void {
|
|
||||||
this.bookSocketService.handleMultipleBookUpdates(updatedBooks);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
handleBookMetadataUpdate(bookId: number): void {
|
handleBookMetadataUpdate(bookId: number): void {
|
||||||
this.bookSocketService.handleBookMetadataUpdate(bookId);
|
this.bookSocketService.handleBookMetadataUpdate(bookId);
|
||||||
}
|
}
|
||||||
|
|
||||||
handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void {
|
handleMultipleBookCoverPatches(patches: readonly BookCoverPatch[]): void {
|
||||||
this.bookSocketService.handleMultipleBookCoverPatches(patches);
|
this.bookSocketService.handleMultipleBookCoverPatches(patches);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
handleTaskProgress(payload: TaskProgressPayload): void {
|
||||||
|
this.bookSocketService.handleTaskProgress(payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
handleReconnect(): void {
|
||||||
|
this.bookSocketService.handleReconnect();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||||
|
import {beforeEach, describe, expect, it} from 'vitest';
|
||||||
|
|
||||||
|
import {Book} from '../model/book.model';
|
||||||
|
import {bookQueryKeys} from '../data/book-query-keys';
|
||||||
|
import {
|
||||||
|
invalidateDeletedBookQueries,
|
||||||
|
patchBooksInCacheWith,
|
||||||
|
reconcileBookCacheChangeSet,
|
||||||
|
removeListOnlyBooks,
|
||||||
|
} from './legacy-book-cache';
|
||||||
|
import {
|
||||||
|
BOOKS_QUERY_KEY,
|
||||||
|
bookDetailQueryKey,
|
||||||
|
bookRecommendationsQueryKey
|
||||||
|
} from './book-query-keys';
|
||||||
|
|
||||||
|
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
libraryId: 1,
|
||||||
|
libraryName: 'Test Library',
|
||||||
|
metadata: {
|
||||||
|
bookId: id,
|
||||||
|
title: `Book ${id}`
|
||||||
|
},
|
||||||
|
...overrides
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('legacy book cache adapter', () => {
|
||||||
|
let queryClient: QueryClient;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
queryClient = new QueryClient();
|
||||||
|
});
|
||||||
|
|
||||||
|
function isInvalidated(queryKey: readonly unknown[]): boolean | undefined {
|
||||||
|
return queryClient.getQueryState(queryKey)?.isInvalidated;
|
||||||
|
}
|
||||||
|
|
||||||
|
it('fans a changeset out to both worlds and removes deleted legacy leaves', async () => {
|
||||||
|
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [makeBook(1), makeBook(201), makeBook(401)]);
|
||||||
|
queryClient.setQueryData(bookDetailQueryKey(201, false), makeBook(201));
|
||||||
|
queryClient.setQueryData(bookDetailQueryKey(401, false), makeBook(401));
|
||||||
|
queryClient.setQueryData(bookRecommendationsQueryKey(1, 20), []);
|
||||||
|
queryClient.setQueryData(bookQueryKeys.detail(201, false), makeBook(201));
|
||||||
|
|
||||||
|
await reconcileBookCacheChangeSet(
|
||||||
|
queryClient,
|
||||||
|
{deletedBookIds: [1], changedBookIds: [201]},
|
||||||
|
{legacyList: 'needs-refetch'},
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(isInvalidated(BOOKS_QUERY_KEY)).toBe(true);
|
||||||
|
expect(isInvalidated(bookDetailQueryKey(201, false))).toBe(true);
|
||||||
|
expect(isInvalidated(bookDetailQueryKey(401, false))).toBe(false);
|
||||||
|
expect(queryClient.getQueryData(bookRecommendationsQueryKey(1, 20))).toBeUndefined();
|
||||||
|
expect(isInvalidated(bookQueryKeys.detail(201, false))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves the surgically patched legacy list fresh while invalidating dependents', () => {
|
||||||
|
const original = makeBook(1);
|
||||||
|
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [original]);
|
||||||
|
queryClient.setQueryData(bookDetailQueryKey(1, false), original);
|
||||||
|
queryClient.setQueryData(bookQueryKeys.detail(1, false), original);
|
||||||
|
|
||||||
|
patchBooksInCacheWith(queryClient, [
|
||||||
|
{bookId: 1, updater: book => ({...book, metadata: {...book.metadata!, titleLocked: true}})},
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)![0].metadata!.titleLocked).toBe(true);
|
||||||
|
expect(isInvalidated(BOOKS_QUERY_KEY)).toBe(false);
|
||||||
|
expect(isInvalidated(bookDetailQueryKey(1, false))).toBe(true);
|
||||||
|
expect(isInvalidated(bookQueryKeys.detail(1, false))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does nothing for an empty changeset', async () => {
|
||||||
|
const book = makeBook(1);
|
||||||
|
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [book]);
|
||||||
|
queryClient.setQueryData(bookQueryKeys.detail(1, false), book);
|
||||||
|
|
||||||
|
patchBooksInCacheWith(queryClient, []);
|
||||||
|
invalidateDeletedBookQueries(queryClient, []);
|
||||||
|
await removeListOnlyBooks(queryClient, []);
|
||||||
|
|
||||||
|
expect(isInvalidated(BOOKS_QUERY_KEY)).toBe(false);
|
||||||
|
expect(isInvalidated(bookQueryKeys.detail(1, false))).toBe(false);
|
||||||
|
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([book]);
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||||
|
|
||||||
|
import {
|
||||||
|
invalidateAllBookQueries,
|
||||||
|
applyBookQueryChangeSet,
|
||||||
|
} from '../data/book-query-cache';
|
||||||
|
import {Book, BookMetadata} from '../model/book.model';
|
||||||
|
import {
|
||||||
|
BOOK_DETAIL_QUERY_PREFIX,
|
||||||
|
BOOK_RECOMMENDATIONS_QUERY_PREFIX,
|
||||||
|
BOOKS_QUERY_KEY,
|
||||||
|
bookDetailQueryPrefix,
|
||||||
|
bookRecommendationsQueryPrefix,
|
||||||
|
} from './book-query-keys';
|
||||||
|
|
||||||
|
export interface BookCoverPatch {
|
||||||
|
readonly id: number;
|
||||||
|
readonly coverUpdatedOn: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BookCacheChangeSet {
|
||||||
|
readonly changedBookIds?: Iterable<number>;
|
||||||
|
readonly deletedBookIds?: Iterable<number>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NormalizedBookCacheChangeSet {
|
||||||
|
readonly changedBookIds: ReadonlySet<number>;
|
||||||
|
readonly deletedBookIds: ReadonlySet<number>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BookCacheReconciliationOptions {
|
||||||
|
readonly legacyList: 'already-updated' | 'needs-refetch';
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeLegacyBookQueries(queryClient: QueryClient, bookIds: Iterable<number>): void {
|
||||||
|
for (const bookId of bookIds) {
|
||||||
|
queryClient.removeQueries({queryKey: bookDetailQueryPrefix(bookId)});
|
||||||
|
queryClient.removeQueries({queryKey: bookRecommendationsQueryPrefix(bookId)});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function reconcileLegacyBookChangeSet(
|
||||||
|
queryClient: QueryClient,
|
||||||
|
changeSet: NormalizedBookCacheChangeSet,
|
||||||
|
): Promise<void> {
|
||||||
|
removeLegacyBookQueries(queryClient, changeSet.deletedBookIds);
|
||||||
|
|
||||||
|
await Promise.all([
|
||||||
|
queryClient.invalidateQueries({queryKey: BOOKS_QUERY_KEY, exact: true}),
|
||||||
|
...[...changeSet.changedBookIds].map(bookId => queryClient.invalidateQueries({
|
||||||
|
queryKey: bookDetailQueryPrefix(bookId),
|
||||||
|
})),
|
||||||
|
invalidateLegacyBookRecommendations(queryClient),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function invalidateAllLegacyBooks(queryClient: QueryClient): Promise<void> {
|
||||||
|
await Promise.all([
|
||||||
|
queryClient.invalidateQueries({queryKey: BOOKS_QUERY_KEY, exact: true}),
|
||||||
|
queryClient.invalidateQueries({queryKey: BOOK_DETAIL_QUERY_PREFIX}),
|
||||||
|
queryClient.invalidateQueries({queryKey: BOOK_RECOMMENDATIONS_QUERY_PREFIX}),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function invalidateLegacyBookRecommendations(queryClient: QueryClient): Promise<void> {
|
||||||
|
return queryClient.invalidateQueries({queryKey: BOOK_RECOMMENDATIONS_QUERY_PREFIX});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function reconcileBookCacheChangeSet(
|
||||||
|
queryClient: QueryClient,
|
||||||
|
changeSet: BookCacheChangeSet,
|
||||||
|
options: BookCacheReconciliationOptions,
|
||||||
|
): Promise<void> {
|
||||||
|
const deletedBookIds = new Set(changeSet.deletedBookIds ?? []);
|
||||||
|
const changedBookIds = new Set(changeSet.changedBookIds ?? []);
|
||||||
|
if (changedBookIds.size === 0 && deletedBookIds.size === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await Promise.all([
|
||||||
|
options.legacyList === 'needs-refetch'
|
||||||
|
? reconcileLegacyBookChangeSet(queryClient, {changedBookIds, deletedBookIds})
|
||||||
|
: reconcilePatchedLegacyBookChangeSet(queryClient, {changedBookIds, deletedBookIds}),
|
||||||
|
applyBookQueryChangeSet(queryClient, {changedBookIds, deletedBookIds}),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function reconcilePatchedLegacyBookChangeSet(
|
||||||
|
queryClient: QueryClient,
|
||||||
|
changeSet: NormalizedBookCacheChangeSet,
|
||||||
|
): Promise<void> {
|
||||||
|
if (changeSet.changedBookIds.size === 0 && changeSet.deletedBookIds.size === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
removeLegacyBookQueries(queryClient, changeSet.deletedBookIds);
|
||||||
|
await Promise.all([
|
||||||
|
...[...changeSet.changedBookIds].map(bookId => queryClient.invalidateQueries({
|
||||||
|
queryKey: bookDetailQueryPrefix(bookId),
|
||||||
|
})),
|
||||||
|
invalidateLegacyBookRecommendations(queryClient),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function patchListOnlyBookFields(
|
||||||
|
queryClient: QueryClient,
|
||||||
|
updates: readonly {readonly bookId: number; readonly fields: Partial<Book>}[],
|
||||||
|
): Promise<void> {
|
||||||
|
return patchListOnlyBooksWith(queryClient, updates.map(update => ({
|
||||||
|
bookId: update.bookId,
|
||||||
|
updater: book => ({...book, ...update.fields}),
|
||||||
|
})));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function patchListOnlyBooksWith(
|
||||||
|
queryClient: QueryClient,
|
||||||
|
updates: readonly {readonly bookId: number; readonly updater: (book: Book) => Book}[],
|
||||||
|
): Promise<void> {
|
||||||
|
const updaterMap = new Map(updates.map(update => [update.bookId, update.updater]));
|
||||||
|
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||||
|
current?.map(book => updaterMap.get(book.id)?.(book) ?? book)
|
||||||
|
);
|
||||||
|
return reconcilePatchedLegacyBookChangeSet(queryClient, {
|
||||||
|
changedBookIds: new Set(updaterMap.keys()),
|
||||||
|
deletedBookIds: new Set(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeListOnlyBooks(
|
||||||
|
queryClient: QueryClient,
|
||||||
|
bookIds: Iterable<number>,
|
||||||
|
): Promise<void> {
|
||||||
|
const deletedBookIds = new Set(bookIds);
|
||||||
|
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||||
|
current?.filter(book => !deletedBookIds.has(book.id))
|
||||||
|
);
|
||||||
|
return reconcilePatchedLegacyBookChangeSet(queryClient, {
|
||||||
|
changedBookIds: new Set(),
|
||||||
|
deletedBookIds,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function patchBookCoversInCache(
|
||||||
|
queryClient: QueryClient,
|
||||||
|
patches: readonly BookCoverPatch[],
|
||||||
|
): void {
|
||||||
|
const patchMap = new Map(patches.map(patch => [patch.id, patch.coverUpdatedOn]));
|
||||||
|
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||||
|
current?.map(book => {
|
||||||
|
const coverUpdatedOn = patchMap.get(book.id);
|
||||||
|
return coverUpdatedOn && book.metadata
|
||||||
|
? {...book, metadata: {...book.metadata, coverUpdatedOn}}
|
||||||
|
: book;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
void reconcileBookCacheChangeSet(
|
||||||
|
queryClient,
|
||||||
|
{changedBookIds: patchMap.keys()},
|
||||||
|
{legacyList: 'already-updated'},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function invalidateAllBookCaches(queryClient: QueryClient): void {
|
||||||
|
void Promise.all([
|
||||||
|
invalidateAllLegacyBooks(queryClient),
|
||||||
|
invalidateAllBookQueries(queryClient),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function invalidateBooksById(queryClient: QueryClient, bookIds: Iterable<number>): void {
|
||||||
|
void reconcileBookCacheChangeSet(
|
||||||
|
queryClient,
|
||||||
|
{changedBookIds: bookIds},
|
||||||
|
{legacyList: 'needs-refetch'},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function invalidateDeletedBookQueries(queryClient: QueryClient, bookIds: Iterable<number>): void {
|
||||||
|
void reconcileBookCacheChangeSet(
|
||||||
|
queryClient,
|
||||||
|
{deletedBookIds: bookIds},
|
||||||
|
{legacyList: 'needs-refetch'},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function patchBooksInCache(queryClient: QueryClient, updatedBooks: readonly Book[]): void {
|
||||||
|
patchBooksInCacheWith(queryClient, updatedBooks.map(book => ({
|
||||||
|
bookId: book.id,
|
||||||
|
updater: () => book,
|
||||||
|
})));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function upsertBooksInCache(queryClient: QueryClient, updatedBooks: readonly Book[]): void {
|
||||||
|
const updatedMap = new Map(updatedBooks.map(book => [book.id, book]));
|
||||||
|
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current => {
|
||||||
|
if (!current) {
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
const currentBookIds = new Set(current.map(book => book.id));
|
||||||
|
return [
|
||||||
|
...current.map(book => updatedMap.get(book.id) ?? book),
|
||||||
|
...updatedBooks.filter(book => !currentBookIds.has(book.id)),
|
||||||
|
];
|
||||||
|
});
|
||||||
|
void reconcileBookCacheChangeSet(
|
||||||
|
queryClient,
|
||||||
|
{changedBookIds: updatedMap.keys()},
|
||||||
|
{legacyList: 'already-updated'},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function patchBookMetadataInCache(queryClient: QueryClient, bookId: number, metadata: BookMetadata): void {
|
||||||
|
patchBooksInCacheWith(queryClient, [{
|
||||||
|
bookId,
|
||||||
|
updater: book => ({...book, metadata}),
|
||||||
|
}]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function patchBookInCacheWith(queryClient: QueryClient, bookId: number, updater: (book: Book) => Book): void {
|
||||||
|
patchBooksInCacheWith(queryClient, [{bookId, updater}]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function patchBooksInCacheWith(
|
||||||
|
queryClient: QueryClient,
|
||||||
|
updates: readonly {readonly bookId: number; readonly updater: (book: Book) => Book}[],
|
||||||
|
): void {
|
||||||
|
const updatedBookIds = updates.map(update => update.bookId);
|
||||||
|
void Promise.all([
|
||||||
|
patchListOnlyBooksWith(queryClient, updates),
|
||||||
|
applyBookQueryChangeSet(queryClient, {changedBookIds: updatedBookIds}),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function patchBookFieldsInCache(queryClient: QueryClient, updates: {bookId: number; fields: Partial<Book>}[]): void {
|
||||||
|
patchBooksInCacheWith(queryClient, updates.map(update => ({
|
||||||
|
bookId: update.bookId,
|
||||||
|
updater: book => ({...book, ...update.fields}),
|
||||||
|
})));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function patchAttachedBookFilesInCache(
|
||||||
|
queryClient: QueryClient,
|
||||||
|
updatedBook: Book,
|
||||||
|
deletedSourceBookIds: Iterable<number>,
|
||||||
|
): void {
|
||||||
|
const deletedBookIds = new Set(deletedSourceBookIds);
|
||||||
|
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||||
|
current
|
||||||
|
?.filter(book => !deletedBookIds.has(book.id))
|
||||||
|
.map(book => book.id === updatedBook.id ? updatedBook : book)
|
||||||
|
);
|
||||||
|
void reconcileBookCacheChangeSet(
|
||||||
|
queryClient,
|
||||||
|
{changedBookIds: [updatedBook.id], deletedBookIds},
|
||||||
|
{legacyList: 'already-updated'},
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user