refactor(books): initial book command service and shared command options (#2168)
This commit is contained in:
@@ -0,0 +1,31 @@
|
|||||||
|
import {
|
||||||
|
mutationOptions,
|
||||||
|
MutationKey,
|
||||||
|
MutationScope,
|
||||||
|
QueryClient,
|
||||||
|
} from '@tanstack/angular-query-experimental';
|
||||||
|
|
||||||
|
export type CommandOutcome<TData> =
|
||||||
|
| {readonly status: 'success'; readonly data: TData}
|
||||||
|
| {readonly status: 'failure'; readonly error: unknown};
|
||||||
|
|
||||||
|
export function reconcilingMutationOptions<TData, TVariables>({mutationKey, scope, mutationFn, reconcile}: {
|
||||||
|
readonly mutationKey: MutationKey;
|
||||||
|
readonly scope?: MutationScope;
|
||||||
|
readonly mutationFn: (variables: TVariables) => Promise<TData>;
|
||||||
|
readonly reconcile: (
|
||||||
|
outcome: CommandOutcome<TData>,
|
||||||
|
variables: TVariables,
|
||||||
|
client: QueryClient,
|
||||||
|
) => Promise<void>;
|
||||||
|
}) {
|
||||||
|
return mutationOptions({
|
||||||
|
mutationKey,
|
||||||
|
scope,
|
||||||
|
mutationFn,
|
||||||
|
onSuccess: (data, variables, _onMutateResult, {client}) =>
|
||||||
|
reconcile({status: 'success', data}, variables, client),
|
||||||
|
onError: (error, variables, _onMutateResult, {client}) =>
|
||||||
|
reconcile({status: 'failure', error}, variables, client),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
export const bookCommandKeys = {
|
||||||
|
all: () => ['books', 'command'] as const,
|
||||||
|
readStatus: () => [...bookCommandKeys.all(), 'read-status'] as const,
|
||||||
|
deleteBooks: () => [...bookCommandKeys.all(), 'delete'] as const,
|
||||||
|
resetProgress: () => [...bookCommandKeys.all(), 'reset-progress'] as const,
|
||||||
|
metadataAllLocks: () => [...bookCommandKeys.all(), 'metadata', 'all-locks'] as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
export const bookCommandScopes = {
|
||||||
|
readingState: {id: 'books.command.reading-state'} as const,
|
||||||
|
deletion: {id: 'books.command.deletion'} as const,
|
||||||
|
metadata: {id: 'books.command.metadata'} as const,
|
||||||
|
};
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import {describe, expect, it} from 'vitest';
|
||||||
|
|
||||||
|
import {overlayPendingBookState} from './book-command-pending-state';
|
||||||
|
import {type BookSummary} from './book-response.models';
|
||||||
|
|
||||||
|
describe('overlayPendingBookState', () => {
|
||||||
|
const book: BookSummary = {
|
||||||
|
id: 1,
|
||||||
|
libraryId: 2,
|
||||||
|
libraryName: 'Library',
|
||||||
|
readStatus: 'UNREAD',
|
||||||
|
epubProgress: {
|
||||||
|
cfi: 'epubcfi(/6/2)',
|
||||||
|
href: 'chapter-1.xhtml',
|
||||||
|
contentSourceProgressPercent: 40,
|
||||||
|
percentage: 42,
|
||||||
|
ttsPositionCfi: null,
|
||||||
|
},
|
||||||
|
koreaderProgress: {percentage: 17},
|
||||||
|
};
|
||||||
|
const emptyOverlay = {
|
||||||
|
readStatuses: new Map(),
|
||||||
|
progressResets: new Map(),
|
||||||
|
};
|
||||||
|
|
||||||
|
it('preserves identity when no pending state touches the book', () => {
|
||||||
|
expect(overlayPendingBookState(book, emptyOverlay)).toBe(book);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('replaces the read status verbatim', () => {
|
||||||
|
const result = overlayPendingBookState(book, {
|
||||||
|
...emptyOverlay,
|
||||||
|
readStatuses: new Map([[1, 'UNSET']]),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.readStatus).toBe('UNSET');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears grimmory-side progress and read status while a reset is in flight', () => {
|
||||||
|
const result = overlayPendingBookState(book, {
|
||||||
|
...emptyOverlay,
|
||||||
|
progressResets: new Map([[1, 'GRIMMORY' as const]]),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.epubProgress).toBeUndefined();
|
||||||
|
expect(result.readStatus).toBeUndefined();
|
||||||
|
expect(result.koreaderProgress).toEqual(book.koreaderProgress);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears only the named source for a device reset', () => {
|
||||||
|
const result = overlayPendingBookState(book, {
|
||||||
|
...emptyOverlay,
|
||||||
|
progressResets: new Map([[1, 'KOREADER' as const]]),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.koreaderProgress).toBeUndefined();
|
||||||
|
expect(result.epubProgress).toEqual(book.epubProgress);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import {computed, Signal} from '@angular/core';
|
||||||
|
import {injectMutationState, MutationKey} from '@tanstack/angular-query-experimental';
|
||||||
|
|
||||||
|
import {bookCommandKeys} from './book-command-keys';
|
||||||
|
import {
|
||||||
|
BookProgressSource,
|
||||||
|
DeleteBooksVariables,
|
||||||
|
ResetBookProgressVariables,
|
||||||
|
SetBookReadStatusVariables,
|
||||||
|
} from './book-command.models';
|
||||||
|
import {BookReadStatus, BookSummary} from './book-response.models';
|
||||||
|
|
||||||
|
export interface PendingBookOverlay {
|
||||||
|
readonly readStatuses: ReadonlyMap<number, BookReadStatus>;
|
||||||
|
readonly progressResets: ReadonlyMap<number, BookProgressSource>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BookIdsVariables {
|
||||||
|
readonly bookIds: readonly number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function injectPendingBookValues<TVariables extends BookIdsVariables, TValue>(
|
||||||
|
mutationKey: MutationKey,
|
||||||
|
fold: (current: TValue | undefined, variables: TVariables) => TValue,
|
||||||
|
): Signal<ReadonlyMap<number, TValue>> {
|
||||||
|
const pendingVariables = injectMutationState<TVariables>(() => ({
|
||||||
|
filters: {
|
||||||
|
mutationKey,
|
||||||
|
status: 'pending',
|
||||||
|
},
|
||||||
|
select: mutation => mutation.state.variables as TVariables,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return computed(() => {
|
||||||
|
const values = new Map<number, TValue>();
|
||||||
|
for (const variables of pendingVariables()) {
|
||||||
|
for (const bookId of variables.bookIds) {
|
||||||
|
values.set(bookId, fold(values.get(bookId), variables));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return values;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function injectPendingBookReadStatuses(): Signal<ReadonlyMap<number, BookReadStatus>> {
|
||||||
|
return injectPendingBookValues<SetBookReadStatusVariables, BookReadStatus>(
|
||||||
|
bookCommandKeys.readStatus(),
|
||||||
|
(_, variables) => variables.status,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function injectPendingBookProgressResets(): Signal<ReadonlyMap<number, BookProgressSource>> {
|
||||||
|
return injectPendingBookValues<ResetBookProgressVariables, BookProgressSource>(
|
||||||
|
bookCommandKeys.resetProgress(),
|
||||||
|
(_, variables) => variables.source,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function injectPendingBookDeletions(): Signal<ReadonlySet<number>> {
|
||||||
|
const deletions = injectPendingBookValues<DeleteBooksVariables, boolean>(
|
||||||
|
bookCommandKeys.deleteBooks(),
|
||||||
|
() => true,
|
||||||
|
);
|
||||||
|
return computed(() => new Set(deletions().keys()));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function overlayPendingBookState(
|
||||||
|
book: BookSummary,
|
||||||
|
overlay: PendingBookOverlay,
|
||||||
|
): BookSummary {
|
||||||
|
const readStatus = overlay.readStatuses.get(book.id);
|
||||||
|
const progressReset = overlay.progressResets.get(book.id);
|
||||||
|
if (readStatus === undefined && progressReset === undefined) {
|
||||||
|
return book;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...book,
|
||||||
|
...(progressReset === undefined ? {} : {...clearedProgress(progressReset), readStatus: undefined}),
|
||||||
|
...(readStatus === undefined ? {} : {readStatus}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearedProgress(source: BookProgressSource): Partial<BookSummary> {
|
||||||
|
if (source === 'KOREADER') {
|
||||||
|
return {koreaderProgress: undefined};
|
||||||
|
}
|
||||||
|
if (source === 'KOBO') {
|
||||||
|
return {koboProgress: undefined};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
epubProgress: undefined,
|
||||||
|
pdfProgress: undefined,
|
||||||
|
cbxProgress: undefined,
|
||||||
|
audiobookProgress: undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import {describe, expect, it} from 'vitest';
|
||||||
|
|
||||||
|
import {
|
||||||
|
bookCommandChangeSet,
|
||||||
|
DeleteBooksPartialError,
|
||||||
|
requireBookIds,
|
||||||
|
} from './book-command.models';
|
||||||
|
|
||||||
|
describe('requireBookIds', () => {
|
||||||
|
it('rejects an empty selection before any request leaves', () => {
|
||||||
|
expect(() => requireBookIds([])).toThrowError();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes a non-empty selection through', () => {
|
||||||
|
expect(requireBookIds([3, 4])).toEqual([3, 4]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('bookCommandChangeSet', () => {
|
||||||
|
it('maps a success through the command-specific confirmation', () => {
|
||||||
|
const changeSet = bookCommandChangeSet(
|
||||||
|
{status: 'success', data: [7, 9]},
|
||||||
|
[7, 9, 11],
|
||||||
|
bookIds => ({changedBookIds: bookIds}),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(changeSet).toEqual({changedBookIds: [7, 9]});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats an unrecognised failure as touching every requested book', () => {
|
||||||
|
const changeSet = bookCommandChangeSet(
|
||||||
|
{status: 'failure', error: new Error('boom')},
|
||||||
|
[7, 9, 11],
|
||||||
|
() => ({changedBookIds: []}),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(changeSet).toEqual({changedBookIds: [7, 9, 11]});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps completed chunks and refetches attempted ones on partial failure', () => {
|
||||||
|
const error = new DeleteBooksPartialError(
|
||||||
|
{removedBookIds: [1, 2], fileCleanupFailedBookIds: []},
|
||||||
|
[3, 4],
|
||||||
|
new Error('boom'),
|
||||||
|
);
|
||||||
|
const changeSet = bookCommandChangeSet(
|
||||||
|
{status: 'failure', error},
|
||||||
|
[1, 2, 3, 4],
|
||||||
|
() => ({changedBookIds: []}),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(changeSet).toEqual({deletedBookIds: [1, 2], changedBookIds: [3, 4]});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import {CommandOutcome} from '../../../core/data/command-options';
|
||||||
|
import {KnownBookReadStatus} from './book-response.models';
|
||||||
|
import {BookQueryChangeSet} from './book-query-cache';
|
||||||
|
|
||||||
|
export interface SetBookReadStatusVariables {
|
||||||
|
readonly bookIds: readonly number[];
|
||||||
|
readonly status: KnownBookReadStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SetBookReadStatusResult {
|
||||||
|
readonly bookId: number;
|
||||||
|
readonly readStatus: KnownBookReadStatus;
|
||||||
|
readonly readStatusModifiedTime?: string | null;
|
||||||
|
readonly dateFinished?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DeleteBooksVariables {
|
||||||
|
readonly bookIds: readonly number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DeleteBooksResult {
|
||||||
|
readonly removedBookIds: readonly number[];
|
||||||
|
readonly fileCleanupFailedBookIds: readonly number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BookProgressSource = 'GRIMMORY' | 'KOREADER' | 'KOBO';
|
||||||
|
|
||||||
|
export interface ResetBookProgressVariables {
|
||||||
|
readonly bookIds: readonly number[];
|
||||||
|
readonly source: BookProgressSource;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ResetBookProgressResult {
|
||||||
|
readonly bookId: number;
|
||||||
|
readonly source: BookProgressSource;
|
||||||
|
readonly readStatusModifiedTime: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export abstract class BulkBookCommandPartialError<TCompleted> extends Error {
|
||||||
|
constructor(
|
||||||
|
readonly completed: TCompleted,
|
||||||
|
readonly attemptedBookIds: readonly number[],
|
||||||
|
override readonly cause: unknown,
|
||||||
|
) {
|
||||||
|
super('Bulk book command stopped before completing.', {cause});
|
||||||
|
this.name = 'BulkBookCommandPartialError';
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract get changeSet(): BookQueryChangeSet;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class DeleteBooksPartialError extends BulkBookCommandPartialError<DeleteBooksResult> {
|
||||||
|
constructor(
|
||||||
|
completed: DeleteBooksResult,
|
||||||
|
attemptedBookIds: readonly number[],
|
||||||
|
cause: unknown,
|
||||||
|
) {
|
||||||
|
super(completed, attemptedBookIds, cause);
|
||||||
|
this.name = 'DeleteBooksPartialError';
|
||||||
|
}
|
||||||
|
|
||||||
|
override get changeSet(): BookQueryChangeSet {
|
||||||
|
return {deletedBookIds: this.completed.removedBookIds};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ResetBookProgressPartialError
|
||||||
|
extends BulkBookCommandPartialError<readonly ResetBookProgressResult[]> {
|
||||||
|
constructor(
|
||||||
|
completed: readonly ResetBookProgressResult[],
|
||||||
|
attemptedBookIds: readonly number[],
|
||||||
|
cause: unknown,
|
||||||
|
) {
|
||||||
|
super(completed, attemptedBookIds, cause);
|
||||||
|
this.name = 'ResetBookProgressPartialError';
|
||||||
|
}
|
||||||
|
|
||||||
|
override get changeSet(): BookQueryChangeSet {
|
||||||
|
return {changedBookIds: this.completed.map(result => result.bookId)};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requireBookIds(bookIds: readonly number[]): readonly number[] {
|
||||||
|
if (bookIds.length === 0) {
|
||||||
|
throw new Error('At least one book ID is required.');
|
||||||
|
}
|
||||||
|
return bookIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function bookCommandChangeSet<TData>(
|
||||||
|
outcome: CommandOutcome<TData>,
|
||||||
|
requestedBookIds: readonly number[],
|
||||||
|
confirmed: (data: TData) => BookQueryChangeSet,
|
||||||
|
): BookQueryChangeSet {
|
||||||
|
return outcome.status === 'success'
|
||||||
|
? confirmed(outcome.data)
|
||||||
|
: bookFailureChangeSet(outcome.error, requestedBookIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
function bookFailureChangeSet(
|
||||||
|
error: unknown,
|
||||||
|
requestedBookIds: readonly number[],
|
||||||
|
): BookQueryChangeSet {
|
||||||
|
if (error instanceof BulkBookCommandPartialError) {
|
||||||
|
const changeSet = error.changeSet;
|
||||||
|
return {
|
||||||
|
...changeSet,
|
||||||
|
changedBookIds: [...(changeSet.changedBookIds ?? []), ...error.attemptedBookIds],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {changedBookIds: requestedBookIds};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SetAllBookMetadataLocksVariables {
|
||||||
|
readonly bookIds: readonly number[];
|
||||||
|
readonly locked: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SetAllBookMetadataLocksResult {
|
||||||
|
readonly bookId: number;
|
||||||
|
readonly metadataLocks: Readonly<Record<string, boolean>>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import {HttpErrorResponse} from '@angular/common/http';
|
||||||
|
import {HttpTestingController} from '@angular/common/http/testing';
|
||||||
|
import {inject, Injectable} from '@angular/core';
|
||||||
|
import {TestBed} from '@angular/core/testing';
|
||||||
|
import {injectMutation, QueryClient} from '@tanstack/angular-query-experimental';
|
||||||
|
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
|
||||||
|
|
||||||
|
import {API_CONFIG} from '../../../core/config/api-config';
|
||||||
|
import {
|
||||||
|
createQueryClientHarness,
|
||||||
|
flushSignalAndQueryEffects,
|
||||||
|
} from '../../../core/testing/query-testing';
|
||||||
|
import {bookQueryKeys} from './book-query-keys';
|
||||||
|
import {BookCommandService} from './book-command.service';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
class BookCommandHost {
|
||||||
|
private readonly commands = inject(BookCommandService);
|
||||||
|
readonly setReadStatus = injectMutation(() => this.commands.setReadStatus());
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('BookCommandService reconciliation', () => {
|
||||||
|
let host: BookCommandHost;
|
||||||
|
let queryClient: QueryClient;
|
||||||
|
let http: HttpTestingController;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
const harness = createQueryClientHarness();
|
||||||
|
queryClient = harness.queryClient;
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [...harness.providers, BookCommandService, BookCommandHost],
|
||||||
|
});
|
||||||
|
host = TestBed.inject(BookCommandHost);
|
||||||
|
http = TestBed.inject(HttpTestingController);
|
||||||
|
flushSignalAndQueryEffects();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
http.verify();
|
||||||
|
queryClient.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates the requested books even when the command fails', async () => {
|
||||||
|
const detailKey = bookQueryKeys.detail(4, false);
|
||||||
|
queryClient.setQueryData(detailKey, {id: 4});
|
||||||
|
|
||||||
|
const result = host.setReadStatus.mutateAsync({bookIds: [4], status: 'READ'});
|
||||||
|
void result.catch(() => undefined);
|
||||||
|
await Promise.resolve();
|
||||||
|
flushSignalAndQueryEffects();
|
||||||
|
|
||||||
|
http.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/status`).flush(
|
||||||
|
'Unavailable',
|
||||||
|
{status: 503, statusText: 'Service Unavailable'},
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(result).rejects.toBeInstanceOf(HttpErrorResponse);
|
||||||
|
expect(queryClient.getQueryState(detailKey)?.isInvalidated).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
import {HttpClient, HttpParams} 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 {bookCommandKeys, bookCommandScopes} from './book-command-keys';
|
||||||
|
import {
|
||||||
|
bookCommandChangeSet,
|
||||||
|
requireBookIds,
|
||||||
|
DeleteBooksPartialError,
|
||||||
|
DeleteBooksResult,
|
||||||
|
SetAllBookMetadataLocksResult,
|
||||||
|
BookProgressSource,
|
||||||
|
SetBookReadStatusResult,
|
||||||
|
ResetBookProgressPartialError,
|
||||||
|
ResetBookProgressResult,
|
||||||
|
DeleteBooksVariables,
|
||||||
|
ResetBookProgressVariables,
|
||||||
|
SetAllBookMetadataLocksVariables,
|
||||||
|
SetBookReadStatusVariables,
|
||||||
|
} from './book-command.models';
|
||||||
|
import {applyBookQueryChangeSet} from './book-query-cache';
|
||||||
|
import {KnownBookReadStatus} from './book-response.models';
|
||||||
|
|
||||||
|
const DELETE_BOOKS_CHUNK_SIZE = 200;
|
||||||
|
const RESET_PROGRESS_CHUNK_SIZE = 500;
|
||||||
|
|
||||||
|
const RESET_PROGRESS_BACKEND_TYPES = {
|
||||||
|
GRIMMORY: 'BOOKLORE',
|
||||||
|
KOREADER: 'KOREADER',
|
||||||
|
KOBO: 'KOBO',
|
||||||
|
} as const satisfies Record<BookProgressSource, string>;
|
||||||
|
|
||||||
|
@Injectable({providedIn: 'root'})
|
||||||
|
export class BookCommandService {
|
||||||
|
private readonly http = inject(HttpClient);
|
||||||
|
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
||||||
|
|
||||||
|
setReadStatus() {
|
||||||
|
return reconcilingMutationOptions({
|
||||||
|
mutationKey: bookCommandKeys.readStatus(),
|
||||||
|
scope: bookCommandScopes.readingState,
|
||||||
|
mutationFn: (variables: SetBookReadStatusVariables) =>
|
||||||
|
this.postReadStatus(requireBookIds(variables.bookIds), variables.status),
|
||||||
|
reconcile: (outcome, variables, client) => applyBookQueryChangeSet(
|
||||||
|
client,
|
||||||
|
bookCommandChangeSet(outcome, variables.bookIds, results => ({
|
||||||
|
changedBookIds: results.map(result => result.bookId),
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteBooks() {
|
||||||
|
return reconcilingMutationOptions({
|
||||||
|
mutationKey: bookCommandKeys.deleteBooks(),
|
||||||
|
scope: bookCommandScopes.deletion,
|
||||||
|
mutationFn: (variables: DeleteBooksVariables) =>
|
||||||
|
this.deleteBookRecordsInChunks(requireBookIds(variables.bookIds)),
|
||||||
|
reconcile: (outcome, variables, client) => applyBookQueryChangeSet(
|
||||||
|
client,
|
||||||
|
bookCommandChangeSet(outcome, variables.bookIds, ({removedBookIds}) => {
|
||||||
|
const removed = new Set(removedBookIds);
|
||||||
|
return {
|
||||||
|
deletedBookIds: removedBookIds,
|
||||||
|
changedBookIds: variables.bookIds.filter(bookId => !removed.has(bookId)),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
resetProgress() {
|
||||||
|
return reconcilingMutationOptions({
|
||||||
|
mutationKey: bookCommandKeys.resetProgress(),
|
||||||
|
scope: bookCommandScopes.readingState,
|
||||||
|
mutationFn: (variables: ResetBookProgressVariables) =>
|
||||||
|
this.postResetProgressInChunks(requireBookIds(variables.bookIds), variables.source),
|
||||||
|
reconcile: (outcome, variables, client) => applyBookQueryChangeSet(
|
||||||
|
client,
|
||||||
|
bookCommandChangeSet(outcome, variables.bookIds, results => ({
|
||||||
|
changedBookIds: results.map(result => result.bookId),
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
setAllMetadataLocks() {
|
||||||
|
return reconcilingMutationOptions({
|
||||||
|
mutationKey: bookCommandKeys.metadataAllLocks(),
|
||||||
|
scope: bookCommandScopes.metadata,
|
||||||
|
mutationFn: (variables: SetAllBookMetadataLocksVariables) =>
|
||||||
|
this.putAllMetadataLocks(requireBookIds(variables.bookIds), variables.locked),
|
||||||
|
reconcile: (outcome, variables, client) => applyBookQueryChangeSet(
|
||||||
|
client,
|
||||||
|
bookCommandChangeSet(outcome, variables.bookIds, results => ({
|
||||||
|
changedBookIds: results.map(result => result.bookId),
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private postReadStatus(
|
||||||
|
bookIds: readonly number[],
|
||||||
|
status: KnownBookReadStatus,
|
||||||
|
): Promise<readonly SetBookReadStatusResult[]> {
|
||||||
|
return lastValueFrom(this.http.post<readonly SetBookReadStatusResult[]>(
|
||||||
|
`${this.baseUrl}/status`,
|
||||||
|
{bookIds, status},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async deleteBookRecords(
|
||||||
|
bookIds: readonly number[],
|
||||||
|
): Promise<DeleteBooksResult> {
|
||||||
|
const response = await lastValueFrom(this.http.delete<DeleteBooksResponse>(
|
||||||
|
this.baseUrl,
|
||||||
|
{params: new HttpParams().set('ids', bookIds.join(','))},
|
||||||
|
));
|
||||||
|
return {
|
||||||
|
removedBookIds: response.deleted,
|
||||||
|
fileCleanupFailedBookIds: [...new Set(response.failedFileDeletions)],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async deleteBookRecordsInChunks(
|
||||||
|
bookIds: readonly number[],
|
||||||
|
): Promise<DeleteBooksResult> {
|
||||||
|
const removedBookIds: number[] = [];
|
||||||
|
const fileCleanupFailedBookIds: number[] = [];
|
||||||
|
|
||||||
|
for (let offset = 0; offset < bookIds.length; offset += DELETE_BOOKS_CHUNK_SIZE) {
|
||||||
|
const chunk = bookIds.slice(offset, offset + DELETE_BOOKS_CHUNK_SIZE);
|
||||||
|
try {
|
||||||
|
const result = await this.deleteBookRecords(chunk);
|
||||||
|
removedBookIds.push(...result.removedBookIds);
|
||||||
|
fileCleanupFailedBookIds.push(...result.fileCleanupFailedBookIds);
|
||||||
|
} catch (cause) {
|
||||||
|
throw new DeleteBooksPartialError(
|
||||||
|
{removedBookIds, fileCleanupFailedBookIds},
|
||||||
|
chunk,
|
||||||
|
cause,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {removedBookIds, fileCleanupFailedBookIds};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async postResetProgress(
|
||||||
|
bookIds: readonly number[],
|
||||||
|
source: BookProgressSource,
|
||||||
|
): Promise<readonly ResetBookProgressResult[]> {
|
||||||
|
const response = await lastValueFrom(this.http.post<readonly ResetProgressResponseItem[]>(
|
||||||
|
`${this.baseUrl}/reset-progress`,
|
||||||
|
bookIds,
|
||||||
|
{params: {type: RESET_PROGRESS_BACKEND_TYPES[source]}},
|
||||||
|
));
|
||||||
|
return response.map(result => ({
|
||||||
|
bookId: result.bookId,
|
||||||
|
source,
|
||||||
|
readStatusModifiedTime: result.readStatusModifiedTime,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async postResetProgressInChunks(
|
||||||
|
bookIds: readonly number[],
|
||||||
|
source: BookProgressSource,
|
||||||
|
): Promise<readonly ResetBookProgressResult[]> {
|
||||||
|
const completed: ResetBookProgressResult[] = [];
|
||||||
|
|
||||||
|
for (let offset = 0; offset < bookIds.length; offset += RESET_PROGRESS_CHUNK_SIZE) {
|
||||||
|
const chunk = bookIds.slice(offset, offset + RESET_PROGRESS_CHUNK_SIZE);
|
||||||
|
try {
|
||||||
|
completed.push(...await this.postResetProgress(chunk, source));
|
||||||
|
} catch (cause) {
|
||||||
|
throw new ResetBookProgressPartialError(completed, chunk, cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return completed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async putAllMetadataLocks(
|
||||||
|
bookIds: readonly number[],
|
||||||
|
locked: boolean,
|
||||||
|
): Promise<readonly SetAllBookMetadataLocksResult[]> {
|
||||||
|
const response = await lastValueFrom(this.http.put<readonly AllMetadataLockResponse[]>(
|
||||||
|
`${this.baseUrl}/metadata/toggle-all-lock`,
|
||||||
|
{bookIds, lock: locked ? 'LOCK' : 'UNLOCK'},
|
||||||
|
));
|
||||||
|
return decodeAllMetadataLockResults(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DeleteBooksResponse {
|
||||||
|
readonly deleted: readonly number[];
|
||||||
|
readonly failedFileDeletions: readonly number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AllMetadataLockResponse {
|
||||||
|
readonly bookId: number;
|
||||||
|
readonly [field: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeAllMetadataLockResults(
|
||||||
|
response: readonly AllMetadataLockResponse[],
|
||||||
|
): readonly SetAllBookMetadataLocksResult[] {
|
||||||
|
return response.map(({bookId, ...fields}) => {
|
||||||
|
const metadataLocks: Record<string, boolean> = {};
|
||||||
|
for (const [field, value] of Object.entries(fields)) {
|
||||||
|
if (field.endsWith('Locked') && typeof value === 'boolean') {
|
||||||
|
metadataLocks[field] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {bookId, metadataLocks};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ResetProgressResponseItem {
|
||||||
|
readonly bookId: number;
|
||||||
|
readonly readStatusModifiedTime: string | null;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user