refactor(books): add shelf data layer (#2188)

This commit is contained in:
Alex
2026-09-21 13:01:51 +01:00
committed by GitHub
parent 78e132aeee
commit 9be47b7ec0
9 changed files with 213 additions and 1 deletions
@@ -1,6 +1,6 @@
import {describe, expect, it} from 'vitest';
import {overlayPendingBookState} from './book-command-pending-state';
import {overlayPendingBookState, overlayShelfIds} from './book-command-pending-state';
import {type BookSummary} from './book-response.models';
describe('overlayPendingBookState', () => {
@@ -9,6 +9,10 @@ describe('overlayPendingBookState', () => {
libraryId: 2,
libraryName: 'Library',
readStatus: 'UNREAD',
shelves: [
{id: 20, name: 'Remove', publicShelf: false, bookCount: 1},
{id: 30, name: 'Keep', publicShelf: false, bookCount: 1},
],
epubProgress: {
cfi: 'epubcfi(/6/2)',
href: 'chapter-1.xhtml',
@@ -56,4 +60,22 @@ describe('overlayPendingBookState', () => {
expect(result.koreaderProgress).toBeUndefined();
expect(result.epubProgress).toEqual(book.epubProgress);
});
it('leaves shelf membership off the overlaid book', () => {
expect(overlayPendingBookState(book, {
...emptyOverlay,
readStatuses: new Map([[1, 'READ']]),
}).shelves).toBe(book.shelves);
});
it('reports confirmed shelf IDs when nothing is in flight', () => {
expect(overlayShelfIds(book, undefined)).toEqual(new Set([20, 30]));
});
it('applies in-flight assignments and removals to the shelf IDs', () => {
expect(overlayShelfIds(book, {
assignShelfIds: new Set([40]),
unassignShelfIds: new Set([20]),
})).toEqual(new Set([30, 40]));
});
});
@@ -9,6 +9,13 @@ import {
SetBookReadStatusVariables,
} from './book-command.models';
import {BookReadStatus, BookSummary} from './book-response.models';
import {bookShelfCommandKeys} from './book-shelf-command-keys';
import {UpdateBookShelfMembershipVariables} from './book-shelf-command.models';
export interface PendingShelfMembership {
readonly assignShelfIds: ReadonlySet<number>;
readonly unassignShelfIds: ReadonlySet<number>;
}
export interface PendingBookOverlay {
readonly readStatuses: ReadonlyMap<number, BookReadStatus>;
@@ -49,6 +56,27 @@ export function injectPendingBookReadStatuses(): Signal<ReadonlyMap<number, Book
);
}
export function injectPendingBookShelfMembership(): Signal<ReadonlyMap<number, PendingShelfMembership>> {
return injectPendingBookValues<UpdateBookShelfMembershipVariables, PendingShelfMembership>(
bookShelfCommandKeys.updateMembership(),
(current, variables) => {
const assignShelfIds = new Set(current?.assignShelfIds);
const unassignShelfIds = new Set(current?.unassignShelfIds);
for (const shelfId of variables.unassignShelfIds) {
assignShelfIds.delete(shelfId);
unassignShelfIds.add(shelfId);
}
for (const shelfId of variables.assignShelfIds) {
unassignShelfIds.delete(shelfId);
assignShelfIds.add(shelfId);
}
return {assignShelfIds, unassignShelfIds};
},
);
}
export function injectPendingBookProgressResets(): Signal<ReadonlyMap<number, BookProgressSource>> {
return injectPendingBookValues<ResetBookProgressVariables, BookProgressSource>(
bookCommandKeys.resetProgress(),
@@ -95,3 +123,20 @@ function clearedProgress(source: BookProgressSource): Partial<BookSummary> {
audiobookProgress: undefined,
};
}
export function overlayShelfIds(
book: BookSummary,
membership: PendingShelfMembership | undefined,
): ReadonlySet<number> {
const shelfIds = new Set((book.shelves ?? []).map(shelf => shelf.id));
if (!membership) {
return shelfIds;
}
for (const shelfId of membership.unassignShelfIds) {
shelfIds.delete(shelfId);
}
for (const shelfId of membership.assignShelfIds) {
shelfIds.add(shelfId);
}
return shelfIds;
}
@@ -0,0 +1,9 @@
import {bookCommandKeys} from './book-command-keys';
export const bookShelfCommandKeys = {
updateMembership: () => [...bookCommandKeys.all(), 'shelf', 'update-membership'] as const,
};
export const bookShelfCommandScopes = {
regularShelves: {id: 'books.command.shelf'} as const,
};
@@ -0,0 +1,9 @@
export interface UpdateBookShelfMembershipVariables {
readonly bookIds: readonly number[];
readonly assignShelfIds: readonly number[];
readonly unassignShelfIds: readonly number[];
}
export interface UpdateBookShelfMembershipResult {
readonly confirmedBookIds: readonly number[];
}
@@ -0,0 +1,65 @@
import {HttpClient} from '@angular/common/http';
import {inject, Injectable} from '@angular/core';
import {lastValueFrom} from 'rxjs';
import {API_CONFIG} from '../../../core/config/api-config';
import {reconcilingMutationOptions} from '../../../core/data/command-options';
import {bookCommandChangeSet, requireBookIds} from './book-command.models';
import {bookShelfCommandKeys, bookShelfCommandScopes} from './book-shelf-command-keys';
import {
UpdateBookShelfMembershipResult,
UpdateBookShelfMembershipVariables,
} from './book-shelf-command.models';
import {applyBookQueryChangeSet} from './book-query-cache';
import {invalidateShelfDefinitions} from './shelf-definition-query-cache';
@Injectable({providedIn: 'root'})
export class BookShelfCommandService {
private readonly http = inject(HttpClient);
private readonly membershipUrl = `${API_CONFIG.BASE_URL}/api/v1/books/shelves`;
updateMembership() {
return reconcilingMutationOptions({
mutationKey: bookShelfCommandKeys.updateMembership(),
scope: bookShelfCommandScopes.regularShelves,
mutationFn: (variables: UpdateBookShelfMembershipVariables) => this.postMembership(
requireBookIds(variables.bookIds),
variables.assignShelfIds,
variables.unassignShelfIds,
),
reconcile: async (outcome, variables, client) => {
await Promise.all([
applyBookQueryChangeSet(
client,
bookCommandChangeSet(outcome, variables.bookIds, ({confirmedBookIds}) => ({
changedBookIds: confirmedBookIds,
})),
),
invalidateShelfDefinitions(client),
]);
},
});
}
private async postMembership(
bookIds: readonly number[],
assignShelfIds: readonly number[],
unassignShelfIds: readonly number[],
): Promise<UpdateBookShelfMembershipResult> {
const response = await lastValueFrom(this.http.post<readonly MembershipBookResponse[]>(
this.membershipUrl,
{
bookIds,
shelvesToAssign: assignShelfIds,
shelvesToUnassign: unassignShelfIds,
},
));
return {
confirmedBookIds: response.map(book => book.id),
};
}
}
interface MembershipBookResponse {
readonly id: number;
}
@@ -0,0 +1,9 @@
import {QueryClient} from '@tanstack/angular-query-experimental';
import {shelfDefinitionQueryKeys} from './shelf-definition-query-keys';
export function invalidateShelfDefinitions(client: QueryClient): Promise<void> {
return client.invalidateQueries({
queryKey: shelfDefinitionQueryKeys.all(),
});
}
@@ -0,0 +1,4 @@
export const shelfDefinitionQueryKeys = {
all: () => ['shelves', 'query'] as const,
definitions: () => [...shelfDefinitionQueryKeys.all(), 'definitions'] as const,
};
@@ -0,0 +1,38 @@
import {HttpClient} from '@angular/common/http';
import {effect, inject, Injectable} from '@angular/core';
import {queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
import {lastValueFrom, takeUntil} from 'rxjs';
import {API_CONFIG} from '../../../core/config/api-config';
import {abortSignal, QUERY_DEFAULTS} from '../../../core/data/query-transport';
import {ShelfDefinition} from './shelf-definition.models';
import {shelfDefinitionQueryKeys} from './shelf-definition-query-keys';
import {AuthService} from '../../../shared/service/auth.service';
@Injectable({providedIn: 'root'})
export class ShelfDefinitionQueryService {
private readonly http = inject(HttpClient);
private readonly authService = inject(AuthService);
private readonly queryClient = inject(QueryClient);
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/shelves`;
constructor() {
effect(() => {
if (this.authService.token() === null) {
this.queryClient.removeQueries({queryKey: shelfDefinitionQueryKeys.all()});
}
});
}
definitions() {
return queryOptions({
queryKey: shelfDefinitionQueryKeys.definitions(),
queryFn: ({signal}): Promise<ShelfDefinition[]> => lastValueFrom(
this.http.get<ShelfDefinition[]>(this.url).pipe(
takeUntil(abortSignal(signal)),
),
),
...QUERY_DEFAULTS,
});
}
}
@@ -0,0 +1,11 @@
import {IconType} from '../../../shared/icons/icon-selection';
export interface ShelfDefinition {
readonly id: number;
readonly userId: number;
readonly name: string;
readonly icon?: string;
readonly iconType?: IconType;
readonly publicShelf: boolean;
readonly bookCount: number;
}