refactor(books): frontend book query service and pagination basics (#2094)
This commit is contained in:
@@ -0,0 +1,73 @@
|
|||||||
|
import {
|
||||||
|
BrowseFacetGroup,
|
||||||
|
BrowseFacetValue,
|
||||||
|
BrowseLink,
|
||||||
|
BrowsePage,
|
||||||
|
BrowsePageMetadata,
|
||||||
|
} from './browse.models';
|
||||||
|
|
||||||
|
interface RawLink {
|
||||||
|
rel: string | string[];
|
||||||
|
href: string;
|
||||||
|
type: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RawBrowsePage<T> {
|
||||||
|
content: T[];
|
||||||
|
page: BrowsePageMetadata;
|
||||||
|
links: RawLink[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RawFacetLink extends RawLink {
|
||||||
|
title: string;
|
||||||
|
value: string;
|
||||||
|
properties?: {numberOfItems?: number};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RawFacetGroup {
|
||||||
|
metadata: {rel: string; key: string; title: string};
|
||||||
|
links: RawFacetLink[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RawFacetResponse {
|
||||||
|
facets: RawFacetGroup[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapBrowsePage<T>(response: RawBrowsePage<T>): BrowsePage<T> {
|
||||||
|
return {
|
||||||
|
content: response.content,
|
||||||
|
page: response.page,
|
||||||
|
links: response.links.map(mapBrowseLink),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapBrowseFacetGroups(response: RawFacetResponse): BrowseFacetGroup[] {
|
||||||
|
return response.facets.map(group => ({
|
||||||
|
rel: group.metadata.rel,
|
||||||
|
key: group.metadata.key,
|
||||||
|
title: group.metadata.title,
|
||||||
|
values: group.links.map(mapBrowseFacetValue),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapBrowseLink(raw: RawLink): BrowseLink {
|
||||||
|
return {
|
||||||
|
rel: normalizeRel(raw.rel),
|
||||||
|
href: raw.href,
|
||||||
|
type: raw.type,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapBrowseFacetValue(raw: RawFacetLink): BrowseFacetValue {
|
||||||
|
const count = raw.properties?.numberOfItems;
|
||||||
|
return {
|
||||||
|
value: raw.value,
|
||||||
|
title: raw.title,
|
||||||
|
selected: normalizeRel(raw.rel).includes('self'),
|
||||||
|
...(count === undefined ? {} : {count}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeRel(rel: string | string[]): string[] {
|
||||||
|
return Array.isArray(rel) ? rel : [rel];
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import {describe, expect, it} from 'vitest';
|
||||||
|
|
||||||
|
import {BrowsePage, findBrowsePageLink} from './browse.models';
|
||||||
|
|
||||||
|
describe('browse models', () => {
|
||||||
|
it('finds page links by an array relation', () => {
|
||||||
|
const page: BrowsePage<string> = {
|
||||||
|
content: [],
|
||||||
|
page: {
|
||||||
|
number: 0,
|
||||||
|
size: 20,
|
||||||
|
totalElements: 0,
|
||||||
|
totalPages: 0,
|
||||||
|
cursor: 'opaque-cursor',
|
||||||
|
},
|
||||||
|
links: [
|
||||||
|
{rel: ['self'], href: '/api/v1/items/page', type: 'application/json'},
|
||||||
|
{rel: ['next', 'collection'], href: '/api/v1/items/page?cursor=next', type: 'application/json'},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(findBrowsePageLink(page, 'next')?.href).toBe('/api/v1/items/page?cursor=next');
|
||||||
|
expect(findBrowsePageLink(page, 'previous')).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
export interface BrowseLink {
|
||||||
|
rel: string[];
|
||||||
|
href: string;
|
||||||
|
type: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BrowsePageMetadata {
|
||||||
|
number: number;
|
||||||
|
size: number;
|
||||||
|
totalElements: number;
|
||||||
|
totalPages: number;
|
||||||
|
cursor: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BrowsePage<T> {
|
||||||
|
content: T[];
|
||||||
|
page: BrowsePageMetadata;
|
||||||
|
links: BrowseLink[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BrowseFacetValue {
|
||||||
|
value: string;
|
||||||
|
title: string;
|
||||||
|
count?: number;
|
||||||
|
selected: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BrowseFacetGroup {
|
||||||
|
rel: string;
|
||||||
|
key: string;
|
||||||
|
title: string;
|
||||||
|
values: BrowseFacetValue[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BrowseFacetLogic = 'and' | 'or' | 'not';
|
||||||
|
export type BrowseSortDirection = 'asc' | 'desc';
|
||||||
|
|
||||||
|
export interface BrowseSortTerm<Key extends string = string> {
|
||||||
|
key: Key;
|
||||||
|
direction: BrowseSortDirection;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function findBrowsePageLink(
|
||||||
|
page: BrowsePage<unknown>,
|
||||||
|
rel: string,
|
||||||
|
): BrowseLink | undefined {
|
||||||
|
return page.links.find(link => link.rel.includes(rel));
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import {HttpErrorResponse} from '@angular/common/http';
|
||||||
|
import {Observable} from 'rxjs';
|
||||||
|
|
||||||
|
export function retryTransientQueryError(failureCount: number, error: unknown): boolean {
|
||||||
|
if (failureCount >= 2) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return error instanceof HttpErrorResponse && (error.status === 0 || error.status >= 500);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const QUERY_DEFAULTS = {
|
||||||
|
staleTime: 30_000,
|
||||||
|
retry: retryTransientQueryError,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export function abortSignal(signal: AbortSignal): Observable<void> {
|
||||||
|
return new Observable(subscriber => {
|
||||||
|
if (signal.aborted) {
|
||||||
|
subscriber.next();
|
||||||
|
subscriber.complete();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const onAbort = () => {
|
||||||
|
subscriber.next();
|
||||||
|
subscriber.complete();
|
||||||
|
};
|
||||||
|
signal.addEventListener('abort', onAbort, {once: true});
|
||||||
|
return () => signal.removeEventListener('abort', onAbort);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,286 @@
|
|||||||
|
import {QueryClient, QueryObserver} from '@tanstack/angular-query-experimental';
|
||||||
|
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||||
|
|
||||||
|
import {
|
||||||
|
invalidateAllBookQueries,
|
||||||
|
invalidateBookCollections,
|
||||||
|
applyBookQueryChangeSet,
|
||||||
|
} from './book-query-cache';
|
||||||
|
import {bookQueryKeys} from './book-query-keys';
|
||||||
|
import {normalizeBookPageParams} from './book-query-params';
|
||||||
|
|
||||||
|
const firstBook = {id: 1};
|
||||||
|
const secondBook = {id: 2};
|
||||||
|
const pageKey = bookQueryKeys.boundedPage(normalizeBookPageParams({
|
||||||
|
facets: {},
|
||||||
|
facetLogic: 'or',
|
||||||
|
sort: [],
|
||||||
|
size: 20,
|
||||||
|
}));
|
||||||
|
const firstDetailKey = bookQueryKeys.detail(1, false);
|
||||||
|
const secondDetailKey = bookQueryKeys.detail(2, false);
|
||||||
|
const firstRecommendationKey = bookQueryKeys.recommendation(1, 20);
|
||||||
|
const secondRecommendationKey = bookQueryKeys.recommendation(2, 20);
|
||||||
|
|
||||||
|
function seedAllQueryFamilies(queryClient: QueryClient): void {
|
||||||
|
queryClient.setQueryData(pageKey, {content: [firstBook, secondBook]});
|
||||||
|
queryClient.setQueryData(firstDetailKey, firstBook);
|
||||||
|
queryClient.setQueryData(secondDetailKey, secondBook);
|
||||||
|
queryClient.setQueryData(firstRecommendationKey, [secondBook]);
|
||||||
|
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', () => {
|
||||||
|
let queryClient: QueryClient;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
queryClient = new QueryClient();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates every new book query from the root', async () => {
|
||||||
|
seedAllQueryFamilies(queryClient);
|
||||||
|
|
||||||
|
await invalidateAllBookQueries(queryClient);
|
||||||
|
|
||||||
|
for (const query of queryClient.getQueryCache().findAll({queryKey: bookQueryKeys.all()})) {
|
||||||
|
expect(query.state.isInvalidated).toBe(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates only collection queries through the collection action', async () => {
|
||||||
|
seedAllQueryFamilies(queryClient);
|
||||||
|
|
||||||
|
await invalidateBookCollections(queryClient);
|
||||||
|
|
||||||
|
expect(queryClient.getQueryState(pageKey)?.isInvalidated).toBe(true);
|
||||||
|
expect(queryClient.getQueryState(firstDetailKey)?.isInvalidated).toBe(false);
|
||||||
|
expect(queryClient.getQueryState(firstRecommendationKey)?.isInvalidated).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidates changed details and every dependent query family once', async () => {
|
||||||
|
seedAllQueryFamilies(queryClient);
|
||||||
|
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||||
|
|
||||||
|
await applyBookQueryChangeSet(queryClient, {changedBookIds: [1, 1]});
|
||||||
|
|
||||||
|
expect(queryClient.getQueryState(pageKey)?.isInvalidated).toBe(true);
|
||||||
|
expect(queryClient.getQueryState(firstDetailKey)?.isInvalidated).toBe(true);
|
||||||
|
expect(queryClient.getQueryState(secondDetailKey)?.isInvalidated).toBe(false);
|
||||||
|
expect(queryClient.getQueryState(firstRecommendationKey)?.isInvalidated).toBe(true);
|
||||||
|
expect(invalidateQueriesSpy).toHaveBeenCalledTimes(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves without work when no changed or deleted book IDs are provided', async () => {
|
||||||
|
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||||
|
const removeQueriesSpy = vi.spyOn(queryClient, 'removeQueries');
|
||||||
|
|
||||||
|
const reconciliation = applyBookQueryChangeSet(queryClient, {
|
||||||
|
changedBookIds: [],
|
||||||
|
deletedBookIds: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(reconciliation).toBeInstanceOf(Promise);
|
||||||
|
await reconciliation;
|
||||||
|
|
||||||
|
expect(invalidateQueriesSpy).not.toHaveBeenCalled();
|
||||||
|
expect(removeQueriesSpy).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('removes deleted leaves and invalidates surviving dependents once', async () => {
|
||||||
|
seedAllQueryFamilies(queryClient);
|
||||||
|
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||||
|
const removeQueriesSpy = vi.spyOn(queryClient, 'removeQueries');
|
||||||
|
|
||||||
|
await applyBookQueryChangeSet(queryClient, {deletedBookIds: [1, 1]});
|
||||||
|
|
||||||
|
expect(queryClient.getQueryData(firstDetailKey)).toBeUndefined();
|
||||||
|
expect(queryClient.getQueryData(firstRecommendationKey)).toBeUndefined();
|
||||||
|
expect(queryClient.getQueryData(secondDetailKey)).toEqual(secondBook);
|
||||||
|
expect(queryClient.getQueryData(secondRecommendationKey)).toEqual([firstBook]);
|
||||||
|
expect(queryClient.getQueryState(pageKey)?.isInvalidated).toBe(true);
|
||||||
|
expect(queryClient.getQueryState(secondRecommendationKey)?.isInvalidated).toBe(true);
|
||||||
|
expect(removeQueriesSpy).toHaveBeenCalledTimes(1);
|
||||||
|
expect(invalidateQueriesSpy).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refetches each active dependent once without aborting it after a change', async () => {
|
||||||
|
const page = observeActiveQuery(queryClient, pageKey, {content: [firstBook]});
|
||||||
|
const detail = observeActiveQuery(queryClient, firstDetailKey, firstBook);
|
||||||
|
const recommendations = observeActiveQuery(queryClient, firstRecommendationKey, [secondBook]);
|
||||||
|
|
||||||
|
const reconciliation = applyBookQueryChangeSet(queryClient, {changedBookIds: [1, 1]});
|
||||||
|
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(page.fetchCount()).toBe(1);
|
||||||
|
expect(detail.fetchCount()).toBe(1);
|
||||||
|
expect(recommendations.fetchCount()).toBe(1);
|
||||||
|
});
|
||||||
|
expect(page.abortCount()).toBe(0);
|
||||||
|
expect(detail.abortCount()).toBe(0);
|
||||||
|
expect(recommendations.abortCount()).toBe(0);
|
||||||
|
|
||||||
|
let settled = false;
|
||||||
|
void reconciliation.then(() => {
|
||||||
|
settled = true;
|
||||||
|
});
|
||||||
|
await Promise.resolve();
|
||||||
|
expect(settled).toBe(false);
|
||||||
|
|
||||||
|
page.finish();
|
||||||
|
detail.finish();
|
||||||
|
recommendations.finish();
|
||||||
|
await reconciliation;
|
||||||
|
expect(settled).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not refetch removed active leaves and refetches surviving dependents once', async () => {
|
||||||
|
const removedDetail = observeActiveQuery(queryClient, firstDetailKey, firstBook);
|
||||||
|
const removedRecommendations = observeActiveQuery(
|
||||||
|
queryClient,
|
||||||
|
firstRecommendationKey,
|
||||||
|
[secondBook],
|
||||||
|
);
|
||||||
|
const page = observeActiveQuery(queryClient, pageKey, {content: [firstBook, secondBook]});
|
||||||
|
const survivingRecommendations = observeActiveQuery(
|
||||||
|
queryClient,
|
||||||
|
secondRecommendationKey,
|
||||||
|
[firstBook],
|
||||||
|
);
|
||||||
|
|
||||||
|
const reconciliation = applyBookQueryChangeSet(queryClient, {deletedBookIds: [1, 1]});
|
||||||
|
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(page.fetchCount()).toBe(1);
|
||||||
|
expect(survivingRecommendations.fetchCount()).toBe(1);
|
||||||
|
});
|
||||||
|
expect(removedDetail.fetchCount()).toBe(0);
|
||||||
|
expect(removedRecommendations.fetchCount()).toBe(0);
|
||||||
|
expect(removedDetail.abortCount()).toBe(0);
|
||||||
|
expect(removedRecommendations.abortCount()).toBe(0);
|
||||||
|
expect(page.abortCount()).toBe(0);
|
||||||
|
expect(survivingRecommendations.abortCount()).toBe(0);
|
||||||
|
expect(queryClient.getQueryData(firstDetailKey)).toBeUndefined();
|
||||||
|
expect(queryClient.getQueryData(firstRecommendationKey)).toBeUndefined();
|
||||||
|
|
||||||
|
removedDetail.finish();
|
||||||
|
removedRecommendations.finish();
|
||||||
|
page.finish();
|
||||||
|
survivingRecommendations.finish();
|
||||||
|
await reconciliation;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('combines changes and deletions with deletion winning for overlapping IDs', async () => {
|
||||||
|
const changedDetail = observeActiveQuery(queryClient, secondDetailKey, secondBook);
|
||||||
|
const removedDetail = observeActiveQuery(queryClient, firstDetailKey, firstBook);
|
||||||
|
const removedRecommendations = observeActiveQuery(
|
||||||
|
queryClient,
|
||||||
|
firstRecommendationKey,
|
||||||
|
[secondBook],
|
||||||
|
);
|
||||||
|
const page = observeActiveQuery(queryClient, pageKey, {content: [firstBook, secondBook]});
|
||||||
|
const survivingRecommendations = observeActiveQuery(
|
||||||
|
queryClient,
|
||||||
|
secondRecommendationKey,
|
||||||
|
[firstBook],
|
||||||
|
);
|
||||||
|
|
||||||
|
const reconciliation = applyBookQueryChangeSet(queryClient, {
|
||||||
|
changedBookIds: [1, 2, 2],
|
||||||
|
deletedBookIds: [1, 1],
|
||||||
|
});
|
||||||
|
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(changedDetail.fetchCount()).toBe(1);
|
||||||
|
expect(page.fetchCount()).toBe(1);
|
||||||
|
expect(survivingRecommendations.fetchCount()).toBe(1);
|
||||||
|
});
|
||||||
|
expect(removedDetail.fetchCount()).toBe(0);
|
||||||
|
expect(removedRecommendations.fetchCount()).toBe(0);
|
||||||
|
expect(changedDetail.abortCount()).toBe(0);
|
||||||
|
expect(removedDetail.abortCount()).toBe(0);
|
||||||
|
expect(removedRecommendations.abortCount()).toBe(0);
|
||||||
|
expect(page.abortCount()).toBe(0);
|
||||||
|
expect(survivingRecommendations.abortCount()).toBe(0);
|
||||||
|
expect(queryClient.getQueryData(firstDetailKey)).toBeUndefined();
|
||||||
|
expect(queryClient.getQueryData(firstRecommendationKey)).toBeUndefined();
|
||||||
|
|
||||||
|
changedDetail.finish();
|
||||||
|
removedDetail.finish();
|
||||||
|
removedRecommendations.finish();
|
||||||
|
page.finish();
|
||||||
|
survivingRecommendations.finish();
|
||||||
|
await reconciliation;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps root invalidation pending until active refetches settle', async () => {
|
||||||
|
const detail = observeActiveQuery(queryClient, firstDetailKey, firstBook);
|
||||||
|
|
||||||
|
const invalidation = invalidateAllBookQueries(queryClient);
|
||||||
|
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(detail.fetchCount()).toBe(1);
|
||||||
|
});
|
||||||
|
let settled = false;
|
||||||
|
void invalidation.then(() => {
|
||||||
|
settled = true;
|
||||||
|
});
|
||||||
|
await Promise.resolve();
|
||||||
|
expect(settled).toBe(false);
|
||||||
|
|
||||||
|
detail.finish();
|
||||||
|
await invalidation;
|
||||||
|
expect(settled).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps collection invalidation pending until active collection refetches settle', async () => {
|
||||||
|
const page = observeActiveQuery(queryClient, pageKey, {content: [firstBook]});
|
||||||
|
const detail = observeActiveQuery(queryClient, firstDetailKey, firstBook);
|
||||||
|
|
||||||
|
const invalidation = invalidateBookCollections(queryClient);
|
||||||
|
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(page.fetchCount()).toBe(1);
|
||||||
|
});
|
||||||
|
expect(detail.fetchCount()).toBe(0);
|
||||||
|
let settled = false;
|
||||||
|
void invalidation.then(() => {
|
||||||
|
settled = true;
|
||||||
|
});
|
||||||
|
await Promise.resolve();
|
||||||
|
expect(settled).toBe(false);
|
||||||
|
|
||||||
|
page.finish();
|
||||||
|
detail.finish();
|
||||||
|
await invalidation;
|
||||||
|
expect(settled).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||||
|
|
||||||
|
import {bookQueryKeys} from './book-query-keys';
|
||||||
|
|
||||||
|
function uniqueBookIds(bookIds: Iterable<number>): Set<number> {
|
||||||
|
return new Set(bookIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookQueryChangeSet {
|
||||||
|
readonly changedBookIds?: Iterable<number>;
|
||||||
|
readonly deletedBookIds?: Iterable<number>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function invalidateAllBookQueries(queryClient: QueryClient): Promise<void> {
|
||||||
|
return queryClient.invalidateQueries({queryKey: bookQueryKeys.all()});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function invalidateBookCollections(queryClient: QueryClient): Promise<void> {
|
||||||
|
return queryClient.invalidateQueries({queryKey: bookQueryKeys.collections()});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function invalidateBookRecommendations(queryClient: QueryClient): Promise<void> {
|
||||||
|
return queryClient.invalidateQueries({queryKey: bookQueryKeys.recommendations()});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function applyBookQueryChangeSet(
|
||||||
|
queryClient: QueryClient,
|
||||||
|
update: BookQueryChangeSet,
|
||||||
|
): Promise<void> {
|
||||||
|
const deletedBookIds = uniqueBookIds(update.deletedBookIds ?? []);
|
||||||
|
const changedBookIds = uniqueBookIds(update.changedBookIds ?? []);
|
||||||
|
for (const bookId of deletedBookIds) {
|
||||||
|
changedBookIds.delete(bookId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (changedBookIds.size === 0 && deletedBookIds.size === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (deletedBookIds.size > 0) {
|
||||||
|
queryClient.removeQueries({
|
||||||
|
predicate: ({queryKey}) =>
|
||||||
|
isBookLeafKey(queryKey, bookQueryKeys.details(), deletedBookIds)
|
||||||
|
|| isBookLeafKey(queryKey, bookQueryKeys.recommendations(), deletedBookIds),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await Promise.all([
|
||||||
|
invalidateBookCollections(queryClient),
|
||||||
|
...(changedBookIds.size > 0 ? [queryClient.invalidateQueries({
|
||||||
|
predicate: ({queryKey}) => isBookLeafKey(queryKey, bookQueryKeys.details(), changedBookIds),
|
||||||
|
})] : []),
|
||||||
|
invalidateBookRecommendations(queryClient),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isBookLeafKey(
|
||||||
|
queryKey: readonly unknown[],
|
||||||
|
prefix: readonly string[],
|
||||||
|
bookIds: ReadonlySet<number>,
|
||||||
|
): boolean {
|
||||||
|
return prefix.every((part, index) => queryKey[index] === part)
|
||||||
|
&& bookIds.has(queryKey[prefix.length] as number);
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import {describe, expect, it} from 'vitest';
|
||||||
|
|
||||||
|
import {
|
||||||
|
normalizeBookCollectionFilterParams,
|
||||||
|
normalizeBookQueryParams,
|
||||||
|
normalizeBookPageParams,
|
||||||
|
} from './book-query-params';
|
||||||
|
import {bookQueryKeys} from './book-query-keys';
|
||||||
|
|
||||||
|
describe('book query keys', () => {
|
||||||
|
const query = {
|
||||||
|
query: 'dune',
|
||||||
|
facets: {genre: ['Fantasy']} as const,
|
||||||
|
facetLogic: 'or' as const,
|
||||||
|
sort: [{key: 'title', direction: 'asc'}] as const,
|
||||||
|
};
|
||||||
|
const page = normalizeBookPageParams({...query, size: 20});
|
||||||
|
|
||||||
|
it('roots every read under the unified book-query prefix', () => {
|
||||||
|
const keys = [
|
||||||
|
bookQueryKeys.boundedPage(page),
|
||||||
|
bookQueryKeys.infinitePage(page),
|
||||||
|
bookQueryKeys.facets(normalizeBookCollectionFilterParams(query)),
|
||||||
|
bookQueryKeys.ids(normalizeBookQueryParams(query)),
|
||||||
|
bookQueryKeys.detail(12, true),
|
||||||
|
bookQueryKeys.recommendation(12, 20),
|
||||||
|
];
|
||||||
|
|
||||||
|
expect(bookQueryKeys.all()).toEqual(['books', 'query']);
|
||||||
|
for (const key of keys) {
|
||||||
|
expect(key.slice(0, 2)).toEqual(bookQueryKeys.all());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps bounded and infinite data shapes on different leaves', () => {
|
||||||
|
expect(bookQueryKeys.boundedPage(page)).not.toEqual(bookQueryKeys.infinitePage(page));
|
||||||
|
expect(bookQueryKeys.boundedPage(page).at(-1)).toBe(page);
|
||||||
|
expect(bookQueryKeys.infinitePage(page).at(-1)).toBe(page);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps facet selection as part of query identity', () => {
|
||||||
|
const genreSelected = normalizeBookCollectionFilterParams(query);
|
||||||
|
const unfiltered = normalizeBookCollectionFilterParams({...query, facets: {}});
|
||||||
|
|
||||||
|
expect(bookQueryKeys.facets(genreSelected)).not.toEqual(bookQueryKeys.facets(unfiltered));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('nests every leaf under the prefix its invalidation targets', () => {
|
||||||
|
const detailPrefix = bookQueryKeys.detailQueries(12);
|
||||||
|
expect(bookQueryKeys.detail(12, true).slice(0, detailPrefix.length)).toEqual([...detailPrefix]);
|
||||||
|
|
||||||
|
const recommendationPrefix = bookQueryKeys.recommendationQueries(12);
|
||||||
|
expect(bookQueryKeys.recommendation(12, 20).slice(0, recommendationPrefix.length))
|
||||||
|
.toEqual([...recommendationPrefix]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import {
|
||||||
|
BookCollectionFilterParams,
|
||||||
|
BookPageParams,
|
||||||
|
BookQueryParams,
|
||||||
|
} from './book-query-params';
|
||||||
|
|
||||||
|
export const bookQueryKeys = {
|
||||||
|
all: () => ['books', 'query'] as const,
|
||||||
|
collections: () => [...bookQueryKeys.all(), 'collection'] as const,
|
||||||
|
boundedPages: () => [...bookQueryKeys.collections(), 'page', 'bounded'] as const,
|
||||||
|
boundedPage: (params: BookPageParams) =>
|
||||||
|
[...bookQueryKeys.boundedPages(), params] as const,
|
||||||
|
infinitePages: () => [...bookQueryKeys.collections(), 'page', 'infinite'] as const,
|
||||||
|
infinitePage: (params: BookPageParams) =>
|
||||||
|
[...bookQueryKeys.infinitePages(), params] as const,
|
||||||
|
facetQueries: () => [...bookQueryKeys.collections(), 'facets'] as const,
|
||||||
|
facets: (params: BookCollectionFilterParams) =>
|
||||||
|
[...bookQueryKeys.facetQueries(), params] as const,
|
||||||
|
idQueries: () => [...bookQueryKeys.collections(), 'ids'] as const,
|
||||||
|
ids: (params: BookQueryParams) =>
|
||||||
|
[...bookQueryKeys.idQueries(), params] as const,
|
||||||
|
details: () => [...bookQueryKeys.all(), 'detail'] as const,
|
||||||
|
detailQueries: (bookId: number) =>
|
||||||
|
[...bookQueryKeys.details(), bookId] as const,
|
||||||
|
detail: (bookId: number, withDescription: boolean) =>
|
||||||
|
[...bookQueryKeys.detailQueries(bookId), {withDescription}] as const,
|
||||||
|
recommendations: () => [...bookQueryKeys.all(), 'recommendation'] as const,
|
||||||
|
recommendationQueries: (bookId: number) =>
|
||||||
|
[...bookQueryKeys.recommendations(), bookId] as const,
|
||||||
|
recommendation: (bookId: number, limit: number) =>
|
||||||
|
[...bookQueryKeys.recommendationQueries(bookId), {limit}] as const,
|
||||||
|
};
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import {describe, expect, it} from 'vitest';
|
||||||
|
|
||||||
|
import {
|
||||||
|
normalizeBookCollectionFilterParams,
|
||||||
|
normalizeBookQueryParams,
|
||||||
|
normalizeBookPageParams,
|
||||||
|
toCollectionHttpParams,
|
||||||
|
toIdsHttpParams,
|
||||||
|
toPageHttpParams,
|
||||||
|
} from './book-query-params';
|
||||||
|
|
||||||
|
describe('book query parameters', () => {
|
||||||
|
it('normalizes equivalent queries and facet selections', () => {
|
||||||
|
const first = normalizeBookPageParams({
|
||||||
|
query: ' dune ',
|
||||||
|
facets: {
|
||||||
|
language: [' French ', 'English'],
|
||||||
|
genre: [' Science Fiction ', 'Fantasy', 'Science Fiction', ' '],
|
||||||
|
},
|
||||||
|
facetLogic: 'or',
|
||||||
|
sort: [{key: 'title', direction: 'asc'}],
|
||||||
|
size: 40,
|
||||||
|
});
|
||||||
|
const second = normalizeBookPageParams({
|
||||||
|
query: 'dune',
|
||||||
|
facets: {
|
||||||
|
genre: ['Fantasy', 'Science Fiction'],
|
||||||
|
language: ['English', 'French'],
|
||||||
|
},
|
||||||
|
facetLogic: 'or',
|
||||||
|
sort: [{key: 'title', direction: 'asc'}],
|
||||||
|
size: 40,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(first).toEqual(second);
|
||||||
|
expect(first.facets).toEqual({
|
||||||
|
genre: ['Fantasy', 'Science Fiction'],
|
||||||
|
language: ['English', 'French'],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes an empty sort through without imposing a default', () => {
|
||||||
|
const normalized = normalizeBookQueryParams({
|
||||||
|
facets: {},
|
||||||
|
facetLogic: 'or',
|
||||||
|
sort: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(normalized.sort).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['and'] as const)('preserves explicit %s facet logic', facetLogic => {
|
||||||
|
const normalized = normalizeBookQueryParams({facets: {}, facetLogic, sort: []});
|
||||||
|
|
||||||
|
expect(normalized.facetLogic).toBe(facetLogic);
|
||||||
|
expect(toIdsHttpParams(normalized).get('facet_logic')).toBe(facetLogic);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('serializes page parameters using the backend vocabulary', () => {
|
||||||
|
const params = toPageHttpParams(normalizeBookPageParams({
|
||||||
|
query: 'dune',
|
||||||
|
facets: {
|
||||||
|
genre: ['Science Fiction'],
|
||||||
|
shelf: ['magic:12'],
|
||||||
|
},
|
||||||
|
facetLogic: 'not',
|
||||||
|
sort: [
|
||||||
|
{key: 'seriesName', direction: 'asc'},
|
||||||
|
{key: 'seriesNumber', direction: 'desc'},
|
||||||
|
],
|
||||||
|
size: 50,
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(params.get('query')).toBe('dune');
|
||||||
|
expect(params.getAll('facet')).toEqual(['genre:Science Fiction', 'shelf:magic:12']);
|
||||||
|
expect(params.get('facet_logic')).toBe('not');
|
||||||
|
expect(params.get('sort')).toBe('seriesName,-seriesNumber');
|
||||||
|
expect(params.get('size')).toBe('50');
|
||||||
|
expect(params.has('page')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('excludes sort and size from facet requests', () => {
|
||||||
|
const params = toCollectionHttpParams(normalizeBookCollectionFilterParams({
|
||||||
|
query: 'dune',
|
||||||
|
facets: {genre: ['Fantasy']},
|
||||||
|
facetLogic: 'and',
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(params.get('query')).toBe('dune');
|
||||||
|
expect(params.getAll('facet')).toEqual(['genre:Fantasy']);
|
||||||
|
expect(params.get('facet_logic')).toBe('and');
|
||||||
|
expect(params.has('sort')).toBe(false);
|
||||||
|
expect(params.has('size')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not emit facet parameters for an empty selection', () => {
|
||||||
|
const params = toCollectionHttpParams(normalizeBookCollectionFilterParams({
|
||||||
|
facets: {},
|
||||||
|
facetLogic: 'or',
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(params.has('facet')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('includes sort but excludes size from ID requests', () => {
|
||||||
|
const params = toIdsHttpParams(normalizeBookQueryParams({
|
||||||
|
facets: {},
|
||||||
|
facetLogic: 'or',
|
||||||
|
sort: [{key: 'title', direction: 'desc'}],
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(params.get('sort')).toBe('-title');
|
||||||
|
expect(params.has('size')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
import {HttpParams} from '@angular/common/http';
|
||||||
|
|
||||||
|
import {
|
||||||
|
BrowseFacetLogic,
|
||||||
|
BrowseSortDirection,
|
||||||
|
BrowseSortTerm,
|
||||||
|
} from '../../../core/data/browse.models';
|
||||||
|
export const BOOK_QUERY_FACET_KEYS = [
|
||||||
|
'author',
|
||||||
|
'series',
|
||||||
|
'genre',
|
||||||
|
'tag',
|
||||||
|
'mood',
|
||||||
|
'language',
|
||||||
|
'publisher',
|
||||||
|
'library',
|
||||||
|
'shelf',
|
||||||
|
'file_type',
|
||||||
|
'read_status',
|
||||||
|
'personal_rating',
|
||||||
|
'amazon_rating',
|
||||||
|
'goodreads_rating',
|
||||||
|
'hardcover_rating',
|
||||||
|
'ranobedb_rating',
|
||||||
|
'age_rating',
|
||||||
|
'content_rating',
|
||||||
|
'match_score',
|
||||||
|
'published_year',
|
||||||
|
'file_size',
|
||||||
|
'page_count',
|
||||||
|
'shelf_status',
|
||||||
|
'comic_character',
|
||||||
|
'comic_team',
|
||||||
|
'comic_location',
|
||||||
|
'comic_creator',
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export const BOOK_QUERY_SORT_KEYS = [
|
||||||
|
'addedOn',
|
||||||
|
'title',
|
||||||
|
'seriesName',
|
||||||
|
'seriesNumber',
|
||||||
|
'publisher',
|
||||||
|
'publishedDate',
|
||||||
|
'amazonRating',
|
||||||
|
'amazonReviewCount',
|
||||||
|
'goodreadsRating',
|
||||||
|
'goodreadsReviewCount',
|
||||||
|
'hardcoverRating',
|
||||||
|
'hardcoverReviewCount',
|
||||||
|
'ranobedbRating',
|
||||||
|
'narrator',
|
||||||
|
'pageCount',
|
||||||
|
'language',
|
||||||
|
'personalRating',
|
||||||
|
'lastReadTime',
|
||||||
|
'readStatus',
|
||||||
|
'dateFinished',
|
||||||
|
'readingProgress',
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export type BookQueryFacetKey = typeof BOOK_QUERY_FACET_KEYS[number];
|
||||||
|
export type BookQuerySortKey = typeof BOOK_QUERY_SORT_KEYS[number];
|
||||||
|
export type FacetLogic = BrowseFacetLogic;
|
||||||
|
export type FacetValueMap = Readonly<Partial<Record<BookQueryFacetKey, readonly string[]>>>;
|
||||||
|
export type SortDirection = BrowseSortDirection;
|
||||||
|
|
||||||
|
export const EMPTY_FACET_SELECTION: FacetValueMap = {};
|
||||||
|
|
||||||
|
export type BookSortTerm = BrowseSortTerm<BookQuerySortKey>;
|
||||||
|
|
||||||
|
export interface BookCollectionFilterParams {
|
||||||
|
query?: string;
|
||||||
|
facets: FacetValueMap;
|
||||||
|
facetLogic: FacetLogic;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookQueryParams extends BookCollectionFilterParams {
|
||||||
|
sort: readonly BookSortTerm[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookPageParams extends BookQueryParams {
|
||||||
|
size: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookDescriptionOptions {
|
||||||
|
withDescription: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_BOOK_SORT_TERMS: readonly BookSortTerm[] = [{key: 'title', direction: 'asc'}];
|
||||||
|
const BOOK_QUERY_FACET_KEY_SET = new Set<string>(BOOK_QUERY_FACET_KEYS);
|
||||||
|
const BOOK_QUERY_SORT_KEY_SET = new Set<string>(BOOK_QUERY_SORT_KEYS);
|
||||||
|
|
||||||
|
export function isBookQueryFacetKey(value: string): value is BookQueryFacetKey {
|
||||||
|
return BOOK_QUERY_FACET_KEY_SET.has(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isBookQuerySortKey(value: string): value is BookQuerySortKey {
|
||||||
|
return BOOK_QUERY_SORT_KEY_SET.has(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeBookPageParams(params: BookPageParams): BookPageParams {
|
||||||
|
return {
|
||||||
|
...normalizeBookQueryParams(params),
|
||||||
|
size: params.size,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toPageHttpParams(params: BookPageParams): HttpParams {
|
||||||
|
return appendSortParam(toCollectionHttpParams(params), params.sort)
|
||||||
|
.set('size', params.size.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toIdsHttpParams(params: BookQueryParams): HttpParams {
|
||||||
|
return appendSortParam(toCollectionHttpParams(params), params.sort);
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendSortParam(httpParams: HttpParams, sort: readonly BookSortTerm[]): HttpParams {
|
||||||
|
return sort.length === 0 ? httpParams : httpParams.set('sort', serializeSort(sort));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeBookQueryParams(params: BookQueryParams): BookQueryParams {
|
||||||
|
return {
|
||||||
|
...normalizeBookCollectionFilterParams(params),
|
||||||
|
sort: params.sort,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeBookCollectionFilterParams(
|
||||||
|
params: BookCollectionFilterParams,
|
||||||
|
): BookCollectionFilterParams {
|
||||||
|
const query = params.query?.trim();
|
||||||
|
const facets = normalizeFacetValueMap(params.facets);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...(query ? {query} : {}),
|
||||||
|
facets,
|
||||||
|
facetLogic: params.facetLogic,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toCollectionHttpParams(params: BookCollectionFilterParams): HttpParams {
|
||||||
|
let httpParams = new HttpParams().set('facet_logic', params.facetLogic);
|
||||||
|
|
||||||
|
if (params.query) {
|
||||||
|
httpParams = httpParams.set('query', params.query);
|
||||||
|
}
|
||||||
|
|
||||||
|
return appendFacetParams(httpParams, params.facets);
|
||||||
|
}
|
||||||
|
|
||||||
|
function compareCodeUnits(first: string, second: string): number {
|
||||||
|
return first < second ? -1 : first > second ? 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeFacetValueMap(facets: FacetValueMap): FacetValueMap {
|
||||||
|
const normalized = Object.entries(facets)
|
||||||
|
.sort(([first], [second]) => compareCodeUnits(first, second))
|
||||||
|
.map(([key, values]) => [key, [...new Set(values
|
||||||
|
.map(value => value.trim())
|
||||||
|
.filter(Boolean))].sort(compareCodeUnits)] as const)
|
||||||
|
.filter(([, values]) => values.length > 0);
|
||||||
|
|
||||||
|
return Object.fromEntries(normalized);
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendFacetParams(httpParams: HttpParams, facets: FacetValueMap): HttpParams {
|
||||||
|
let result = httpParams;
|
||||||
|
for (const [key, values] of Object.entries(facets)) {
|
||||||
|
for (const value of values) {
|
||||||
|
result = result.append('facet', `${key}:${value}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function serializeSort(sort: readonly BookSortTerm[]): string {
|
||||||
|
return sort
|
||||||
|
.map(term => `${term.direction === 'desc' ? '-' : ''}${term.key}`)
|
||||||
|
.join(',');
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import {describe, expect, it} from 'vitest';
|
||||||
|
|
||||||
|
import {BookPage, flattenBookPages} from './book-query.models';
|
||||||
|
|
||||||
|
function page(ids: number[]): BookPage {
|
||||||
|
return {
|
||||||
|
content: ids.map(id => ({id, libraryId: 1, libraryName: 'Library'})),
|
||||||
|
page: {
|
||||||
|
number: 0,
|
||||||
|
size: ids.length,
|
||||||
|
totalElements: ids.length,
|
||||||
|
totalPages: 1,
|
||||||
|
cursor: 'opaque-cursor',
|
||||||
|
},
|
||||||
|
links: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('flattenBookPages', () => {
|
||||||
|
it('returns an empty list without data', () => {
|
||||||
|
expect(flattenBookPages(undefined)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('flattens pages in order', () => {
|
||||||
|
const flattened = flattenBookPages({
|
||||||
|
pages: [page([1, 2]), page([3, 4])],
|
||||||
|
pageParams: [null, 'next'],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(flattened.map(book => book.id)).toEqual([1, 2, 3, 4]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the first occurrence when an offset shift re-serves a book', () => {
|
||||||
|
const flattened = flattenBookPages({
|
||||||
|
pages: [page([1, 2]), page([2, 3])],
|
||||||
|
pageParams: [null, 'next'],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(flattened.map(book => book.id)).toEqual([1, 2, 3]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import {InfiniteData} from '@tanstack/angular-query-experimental';
|
||||||
|
|
||||||
|
import {BrowseFacetGroup, BrowsePage} from '../../../core/data/browse.models';
|
||||||
|
import {BookSummary} from './book-response.models';
|
||||||
|
|
||||||
|
export type BookPage = BrowsePage<BookSummary>;
|
||||||
|
export type BookFacetGroup = BrowseFacetGroup;
|
||||||
|
|
||||||
|
export function flattenBookPages(
|
||||||
|
data: InfiniteData<BookPage> | undefined,
|
||||||
|
): BookSummary[] {
|
||||||
|
const books = data?.pages.flatMap(page => page.content) ?? [];
|
||||||
|
const seen = new Set<number>();
|
||||||
|
return books.filter(book => {
|
||||||
|
if (seen.has(book.id)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
seen.add(book.id);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
import {HttpErrorResponse} from '@angular/common/http';
|
||||||
|
import {HttpTestingController} from '@angular/common/http/testing';
|
||||||
|
import {Injectable, inject} from '@angular/core';
|
||||||
|
import {TestBed} from '@angular/core/testing';
|
||||||
|
import {injectInfiniteQuery, QueryClient} from '@tanstack/angular-query-experimental';
|
||||||
|
import {afterEach, beforeEach, describe, expect, expectTypeOf, it, vi} from 'vitest';
|
||||||
|
|
||||||
|
import {API_CONFIG} from '../../../core/config/api-config';
|
||||||
|
import {
|
||||||
|
createAuthServiceStub,
|
||||||
|
createQueryClientHarness,
|
||||||
|
flushSignalAndQueryEffects,
|
||||||
|
} from '../../../core/testing/query-testing';
|
||||||
|
import {AuthService} from '../../../shared/service/auth.service';
|
||||||
|
import {bookQueryKeys} from './book-query-keys';
|
||||||
|
import {BookPageParams} from './book-query-params';
|
||||||
|
import {BookPage} from './book-query.models';
|
||||||
|
import {BookDetail, BookRecommendation} from './book-response.models';
|
||||||
|
import {retryTransientQueryError} from '../../../core/data/query-transport';
|
||||||
|
import {BookQueryService} from './book-query.service';
|
||||||
|
|
||||||
|
const PARAMS: BookPageParams = {
|
||||||
|
query: 'dune',
|
||||||
|
facets: {genre: ['Science Fiction']},
|
||||||
|
facetLogic: 'or',
|
||||||
|
sort: [{key: 'title', direction: 'asc'}],
|
||||||
|
size: 20,
|
||||||
|
};
|
||||||
|
|
||||||
|
function page(ids: number[]): BookPage {
|
||||||
|
return {
|
||||||
|
content: ids.map(id => ({id, libraryId: 1, libraryName: 'Library'})),
|
||||||
|
page: {
|
||||||
|
number: 0,
|
||||||
|
size: 20,
|
||||||
|
totalElements: ids.length,
|
||||||
|
totalPages: ids.length === 0 ? 0 : 1,
|
||||||
|
cursor: 'opaque-cursor',
|
||||||
|
},
|
||||||
|
links: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
class InfiniteQueryHost {
|
||||||
|
private readonly books = inject(BookQueryService);
|
||||||
|
readonly query = injectInfiniteQuery(() => this.books.infinitePage(PARAMS));
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('BookQueryService', () => {
|
||||||
|
let service: BookQueryService;
|
||||||
|
let queryClient: QueryClient;
|
||||||
|
let authService: ReturnType<typeof createAuthServiceStub>;
|
||||||
|
let http: HttpTestingController;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
const harness = createQueryClientHarness();
|
||||||
|
queryClient = harness.queryClient;
|
||||||
|
authService = createAuthServiceStub();
|
||||||
|
queryClient.setDefaultOptions({queries: {retry: false}});
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
...harness.providers,
|
||||||
|
{provide: AuthService, useValue: authService},
|
||||||
|
BookQueryService,
|
||||||
|
InfiniteQueryHost,
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
service = TestBed.inject(BookQueryService);
|
||||||
|
http = TestBed.inject(HttpTestingController);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
http.verify();
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('removes its cached book queries when the authenticated session ends', () => {
|
||||||
|
const key = bookQueryKeys.detail(7, false);
|
||||||
|
queryClient.setQueryData(key, {id: 7});
|
||||||
|
|
||||||
|
authService.token.set(null);
|
||||||
|
flushSignalAndQueryEffects();
|
||||||
|
|
||||||
|
expect(queryClient.getQueryData(key)).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches one bounded summary page with normalized parameters', async () => {
|
||||||
|
const resultPromise = queryClient.fetchQuery(service.page(PARAMS));
|
||||||
|
const request = http.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/page?facet_logic=or&query=dune&facet=genre:Science%20Fiction&sort=title&size=20`);
|
||||||
|
request.flush(page([1, 2]));
|
||||||
|
|
||||||
|
await expect(resultPromise).resolves.toMatchObject({
|
||||||
|
content: [{id: 1}, {id: 2}],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends every selected facet value as a repeated facet parameter', async () => {
|
||||||
|
const resultPromise = queryClient.fetchQuery(service.page({
|
||||||
|
...PARAMS,
|
||||||
|
facets: {
|
||||||
|
genre: ['Science Fiction'],
|
||||||
|
language: ['English'],
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
const request = http.expectOne(
|
||||||
|
`${API_CONFIG.BASE_URL}/api/v1/books/page?facet_logic=or&query=dune&facet=genre:Science%20Fiction&facet=language:English&sort=title&size=20`,
|
||||||
|
);
|
||||||
|
request.flush(page([1]));
|
||||||
|
|
||||||
|
await expect(resultPromise).resolves.toMatchObject({content: [{id: 1}]});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches facets without sort or size', async () => {
|
||||||
|
const resultPromise = queryClient.fetchQuery(service.facets(PARAMS));
|
||||||
|
const request = http.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/facets?facet_logic=or&query=dune&facet=genre:Science%20Fiction`);
|
||||||
|
request.flush({
|
||||||
|
links: [{rel: 'self', href: '/api/v1/books/facets?query=dune', type: 'application/json'}],
|
||||||
|
facets: [{
|
||||||
|
metadata: {rel: 'facet', key: 'genre', title: 'Genre'},
|
||||||
|
links: [{
|
||||||
|
rel: ['self', 'facet'],
|
||||||
|
href: '/api/v1/books/page?facet=genre%3AFantasy',
|
||||||
|
type: 'application/json',
|
||||||
|
title: 'Fantasy',
|
||||||
|
value: 'Fantasy',
|
||||||
|
properties: {numberOfItems: 4},
|
||||||
|
}],
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(resultPromise).resolves.toEqual([{
|
||||||
|
rel: 'facet',
|
||||||
|
key: 'genre',
|
||||||
|
title: 'Genre',
|
||||||
|
values: [{value: 'Fantasy', title: 'Fantasy', count: 4, selected: true}],
|
||||||
|
}]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches matching IDs with sort but no size', async () => {
|
||||||
|
const resultPromise = queryClient.fetchQuery(service.ids(PARAMS));
|
||||||
|
const request = http.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/ids?facet_logic=or&query=dune&facet=genre:Science%20Fiction&sort=title`);
|
||||||
|
request.flush([3, 1, 2]);
|
||||||
|
|
||||||
|
await expect(resultPromise).resolves.toEqual([3, 1, 2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('follows the exact next href for an infinite query', async () => {
|
||||||
|
const host = TestBed.inject(InfiniteQueryHost);
|
||||||
|
flushSignalAndQueryEffects();
|
||||||
|
|
||||||
|
const firstRequest = http.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/page?facet_logic=or&query=dune&facet=genre:Science%20Fiction&sort=title&size=20`);
|
||||||
|
expect(firstRequest.request.params.has('cursor')).toBe(false);
|
||||||
|
firstRequest.flush({
|
||||||
|
...page([1]),
|
||||||
|
links: [
|
||||||
|
{
|
||||||
|
rel: 'self',
|
||||||
|
href: '/api/v1/books/page?cursor=origin',
|
||||||
|
type: 'application/json',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
rel: 'next',
|
||||||
|
href: '/api/v1/books/page?facet=genre%3AScience%20Fiction&cursor=opaque',
|
||||||
|
type: 'application/json',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
await vi.waitFor(() => expect(host.query.isSuccess()).toBe(true));
|
||||||
|
|
||||||
|
const nextPromise = host.query.fetchNextPage();
|
||||||
|
const nextRequest = http.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/page?facet=genre%3AScience%20Fiction&cursor=opaque`);
|
||||||
|
nextRequest.flush(page([2]));
|
||||||
|
const nextResult = await nextPromise;
|
||||||
|
|
||||||
|
expect(nextResult.data?.pages.flatMap(current => current.content.map(book => book.id)))
|
||||||
|
.toEqual([1, 2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stops paging when the backend emits no next link', async () => {
|
||||||
|
const host = TestBed.inject(InfiniteQueryHost);
|
||||||
|
flushSignalAndQueryEffects();
|
||||||
|
|
||||||
|
http.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/page?facet_logic=or&query=dune&facet=genre:Science%20Fiction&sort=title&size=20`)
|
||||||
|
.flush(page([1]));
|
||||||
|
await vi.waitFor(() => expect(host.query.isSuccess()).toBe(true));
|
||||||
|
|
||||||
|
expect(host.query.hasNextPage()).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keys an infinite query by its normalized parameters alone so the cache is shared', () => {
|
||||||
|
expect(service.infinitePage(PARAMS).queryKey).toEqual(service.infinitePage(PARAMS).queryKey);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches full book detail with the description flag', async () => {
|
||||||
|
const resultPromise = queryClient.fetchQuery(service.detail(42, {withDescription: true}));
|
||||||
|
expectTypeOf(resultPromise).toEqualTypeOf<Promise<BookDetail>>();
|
||||||
|
const request = http.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/42?withDescription=true`);
|
||||||
|
const response: BookDetail = {
|
||||||
|
id: 42,
|
||||||
|
libraryId: 1,
|
||||||
|
libraryName: 'Library',
|
||||||
|
metadata: {bookId: 42, title: 'Dune', description: 'Desert power.'},
|
||||||
|
};
|
||||||
|
request.flush(response);
|
||||||
|
|
||||||
|
await expect(resultPromise).resolves.toMatchObject({
|
||||||
|
id: 42,
|
||||||
|
metadata: {description: 'Desert power.'},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches recommendations and preserves similarity order', async () => {
|
||||||
|
const resultPromise = queryClient.fetchQuery(service.recommendations(42, 2));
|
||||||
|
expectTypeOf(resultPromise).toEqualTypeOf<Promise<BookRecommendation[]>>();
|
||||||
|
const request = http.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/42/recommendations?limit=2`);
|
||||||
|
const response: BookRecommendation[] = [
|
||||||
|
{book: {id: 8, libraryId: 1, libraryName: 'Library'}, similarityScore: 0.4},
|
||||||
|
{book: {id: 5, libraryId: 1, libraryName: 'Library'}, similarityScore: 0.9},
|
||||||
|
];
|
||||||
|
request.flush(response);
|
||||||
|
|
||||||
|
await expect(resultPromise).resolves.toMatchObject([
|
||||||
|
{book: {id: 8}, similarityScore: 0.4},
|
||||||
|
{book: {id: 5}, similarityScore: 0.9},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cancels an active HTTP request through the query signal', async () => {
|
||||||
|
const options = service.detail(42, {withDescription: false});
|
||||||
|
const resultPromise = queryClient.fetchQuery(options);
|
||||||
|
const request = http.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/42?withDescription=false`);
|
||||||
|
|
||||||
|
await queryClient.cancelQueries({queryKey: options.queryKey});
|
||||||
|
|
||||||
|
expect(request.cancelled).toBe(true);
|
||||||
|
await expect(resultPromise).rejects.toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('retries only transient failures and only twice', () => {
|
||||||
|
const networkError = new HttpErrorResponse({status: 0});
|
||||||
|
const badRequest = new HttpErrorResponse({status: 400});
|
||||||
|
const serverError = new HttpErrorResponse({status: 503});
|
||||||
|
|
||||||
|
expect(retryTransientQueryError(0, networkError)).toBe(true);
|
||||||
|
expect(retryTransientQueryError(0, badRequest)).toBe(false);
|
||||||
|
expect(retryTransientQueryError(0, serverError)).toBe(true);
|
||||||
|
expect(retryTransientQueryError(0, new Error('Unexpected failure'))).toBe(false);
|
||||||
|
expect(retryTransientQueryError(2, serverError)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
import {HttpClient, HttpParams} from '@angular/common/http';
|
||||||
|
import {effect, inject, Injectable} from '@angular/core';
|
||||||
|
import {
|
||||||
|
infiniteQueryOptions,
|
||||||
|
queryOptions,
|
||||||
|
QueryClient,
|
||||||
|
} from '@tanstack/angular-query-experimental';
|
||||||
|
import {lastValueFrom, Observable, map, takeUntil} from 'rxjs';
|
||||||
|
|
||||||
|
import {API_CONFIG} from '../../../core/config/api-config';
|
||||||
|
import {findBrowsePageLink} from '../../../core/data/browse.models';
|
||||||
|
import {mapBrowseFacetGroups, mapBrowsePage} from '../../../core/data/browse-response';
|
||||||
|
import {bookQueryKeys} from './book-query-keys';
|
||||||
|
import {
|
||||||
|
BookCollectionFilterParams,
|
||||||
|
BookDescriptionOptions,
|
||||||
|
BookPageParams,
|
||||||
|
BookQueryParams,
|
||||||
|
normalizeBookCollectionFilterParams,
|
||||||
|
normalizeBookPageParams,
|
||||||
|
normalizeBookQueryParams,
|
||||||
|
toCollectionHttpParams,
|
||||||
|
toIdsHttpParams,
|
||||||
|
toPageHttpParams,
|
||||||
|
} from './book-query-params';
|
||||||
|
import {BookFacetGroup, BookPage} from './book-query.models';
|
||||||
|
import {BookDetail, BookRecommendation, BookSummary} from './book-response.models';
|
||||||
|
import {abortSignal, QUERY_DEFAULTS} from '../../../core/data/query-transport';
|
||||||
|
import {AuthService} from '../../../shared/service/auth.service';
|
||||||
|
|
||||||
|
@Injectable({providedIn: 'root'})
|
||||||
|
export class BookQueryService {
|
||||||
|
private readonly http = inject(HttpClient);
|
||||||
|
private readonly authService = inject(AuthService);
|
||||||
|
private readonly queryClient = inject(QueryClient);
|
||||||
|
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
effect(() => {
|
||||||
|
if (this.authService.token() === null) {
|
||||||
|
this.queryClient.removeQueries({queryKey: bookQueryKeys.all()});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
page(params: BookPageParams) {
|
||||||
|
const normalized = normalizeBookPageParams(params);
|
||||||
|
|
||||||
|
return queryOptions({
|
||||||
|
queryKey: bookQueryKeys.boundedPage(normalized),
|
||||||
|
queryFn: ({signal}) => this.fetchPage(normalized, null, signal),
|
||||||
|
...QUERY_DEFAULTS,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
infinitePage(params: BookPageParams) {
|
||||||
|
const normalized = normalizeBookPageParams(params);
|
||||||
|
|
||||||
|
return infiniteQueryOptions({
|
||||||
|
queryKey: bookQueryKeys.infinitePage(normalized),
|
||||||
|
queryFn: ({pageParam, signal}) => this.fetchPage(normalized, pageParam, signal),
|
||||||
|
initialPageParam: null as string | null,
|
||||||
|
getNextPageParam: page => findBrowsePageLink(page, 'next')?.href,
|
||||||
|
...QUERY_DEFAULTS,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
facets(params: BookCollectionFilterParams) {
|
||||||
|
const normalized = normalizeBookCollectionFilterParams(params);
|
||||||
|
|
||||||
|
return queryOptions({
|
||||||
|
queryKey: bookQueryKeys.facets(normalized),
|
||||||
|
queryFn: ({signal}): Promise<BookFacetGroup[]> => this.getMapped(
|
||||||
|
`${this.baseUrl}/facets`,
|
||||||
|
signal,
|
||||||
|
mapBrowseFacetGroups,
|
||||||
|
toCollectionHttpParams(normalized),
|
||||||
|
),
|
||||||
|
...QUERY_DEFAULTS,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
ids(params: BookQueryParams) {
|
||||||
|
const normalized = normalizeBookQueryParams(params);
|
||||||
|
|
||||||
|
return queryOptions({
|
||||||
|
queryKey: bookQueryKeys.ids(normalized),
|
||||||
|
queryFn: ({signal}) => this.get<number[]>(
|
||||||
|
`${this.baseUrl}/ids`,
|
||||||
|
signal,
|
||||||
|
toIdsHttpParams(normalized),
|
||||||
|
),
|
||||||
|
...QUERY_DEFAULTS,
|
||||||
|
staleTime: 0,
|
||||||
|
gcTime: 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
detail(bookId: number, {withDescription}: BookDescriptionOptions) {
|
||||||
|
return queryOptions({
|
||||||
|
queryKey: bookQueryKeys.detail(bookId, withDescription),
|
||||||
|
queryFn: ({signal}): Promise<BookDetail> => this.get<BookDetail>(
|
||||||
|
`${this.baseUrl}/${bookId}`,
|
||||||
|
signal,
|
||||||
|
new HttpParams().set('withDescription', withDescription.toString()),
|
||||||
|
),
|
||||||
|
...QUERY_DEFAULTS,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
recommendations(bookId: number, limit: number) {
|
||||||
|
return queryOptions({
|
||||||
|
queryKey: bookQueryKeys.recommendation(bookId, limit),
|
||||||
|
queryFn: ({signal}): Promise<BookRecommendation[]> => this.get<BookRecommendation[]>(
|
||||||
|
`${this.baseUrl}/${bookId}/recommendations`,
|
||||||
|
signal,
|
||||||
|
new HttpParams().set('limit', limit.toString()),
|
||||||
|
),
|
||||||
|
...QUERY_DEFAULTS,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private fetchPage(
|
||||||
|
params: BookPageParams,
|
||||||
|
nextHref: string | null,
|
||||||
|
signal: AbortSignal,
|
||||||
|
): Promise<BookPage> {
|
||||||
|
if (nextHref !== null) {
|
||||||
|
return this.getMapped(
|
||||||
|
`${API_CONFIG.BASE_URL}${nextHref}`,
|
||||||
|
signal,
|
||||||
|
mapBrowsePage<BookSummary>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.getMapped(
|
||||||
|
`${this.baseUrl}/page`,
|
||||||
|
signal,
|
||||||
|
mapBrowsePage<BookSummary>,
|
||||||
|
toPageHttpParams(params),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private get<T>(url: string, signal: AbortSignal, params?: HttpParams): Promise<T> {
|
||||||
|
return this.finalize(this.http.get<T>(url, {params}), signal);
|
||||||
|
}
|
||||||
|
|
||||||
|
private getMapped<TRaw, T>(
|
||||||
|
url: string,
|
||||||
|
signal: AbortSignal,
|
||||||
|
project: (value: TRaw) => T,
|
||||||
|
params?: HttpParams,
|
||||||
|
): Promise<T> {
|
||||||
|
return this.finalize(this.http.get<TRaw>(url, {params}).pipe(map(project)), signal);
|
||||||
|
}
|
||||||
|
|
||||||
|
private finalize<T>(source: Observable<T>, signal: AbortSignal): Promise<T> {
|
||||||
|
return lastValueFrom(source.pipe(takeUntil(abortSignal(signal))));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,324 @@
|
|||||||
|
export const BOOK_FILE_TYPES = ['PDF', 'EPUB', 'CBX', 'FB2', 'MOBI', 'AZW3', 'AUDIOBOOK'] as const;
|
||||||
|
export type BookFileType = typeof BOOK_FILE_TYPES[number] | (string & {});
|
||||||
|
|
||||||
|
export const BOOK_ARCHIVE_TYPES = ['ZIP', 'RAR', 'SEVEN_ZIP', 'UNKNOWN'] as const;
|
||||||
|
export type BookArchiveType = typeof BOOK_ARCHIVE_TYPES[number] | (string & {});
|
||||||
|
|
||||||
|
export const BOOK_READ_STATUSES = [
|
||||||
|
'UNREAD',
|
||||||
|
'READING',
|
||||||
|
'RE_READING',
|
||||||
|
'READ',
|
||||||
|
'PARTIALLY_READ',
|
||||||
|
'PAUSED',
|
||||||
|
'WONT_READ',
|
||||||
|
'ABANDONED',
|
||||||
|
'UNSET',
|
||||||
|
] as const;
|
||||||
|
export type KnownBookReadStatus = typeof BOOK_READ_STATUSES[number];
|
||||||
|
export type BookReadStatus = KnownBookReadStatus | (string & {});
|
||||||
|
|
||||||
|
export const BOOK_METADATA_PROVIDERS = [
|
||||||
|
'Amazon',
|
||||||
|
'GoodReads',
|
||||||
|
'Google',
|
||||||
|
'Hardcover',
|
||||||
|
'Comicvine',
|
||||||
|
'Douban',
|
||||||
|
'Lubimyczytac',
|
||||||
|
'Ranobedb',
|
||||||
|
'Audible',
|
||||||
|
] as const;
|
||||||
|
export type BookMetadataProvider = typeof BOOK_METADATA_PROVIDERS[number] | (string & {});
|
||||||
|
|
||||||
|
export interface BookFileResponse {
|
||||||
|
id: number;
|
||||||
|
bookId: number;
|
||||||
|
fileName?: string;
|
||||||
|
filePath?: string;
|
||||||
|
fileSubPath?: string;
|
||||||
|
book: boolean;
|
||||||
|
folderBased: boolean;
|
||||||
|
bookType?: BookFileType;
|
||||||
|
archiveType?: BookArchiveType;
|
||||||
|
fileSizeKb?: number;
|
||||||
|
extension?: string;
|
||||||
|
description?: string;
|
||||||
|
addedOn?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BookShelfIconType = 'LUCIDE' | 'CUSTOM_SVG' | (string & {});
|
||||||
|
|
||||||
|
export type BookShelfSortDirection = 'ASCENDING' | 'DESCENDING';
|
||||||
|
|
||||||
|
export interface BookShelfSort {
|
||||||
|
field: string | null;
|
||||||
|
direction: BookShelfSortDirection | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookShelf {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
icon?: string;
|
||||||
|
iconType?: BookShelfIconType;
|
||||||
|
sort?: BookShelfSort;
|
||||||
|
userId?: number;
|
||||||
|
publicShelf: boolean;
|
||||||
|
bookCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookLibraryPath {
|
||||||
|
id: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookPdfProgress {
|
||||||
|
page: number | null;
|
||||||
|
percentage: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookEpubProgress {
|
||||||
|
cfi: string | null;
|
||||||
|
href: string | null;
|
||||||
|
contentSourceProgressPercent: number | null;
|
||||||
|
percentage: number | null;
|
||||||
|
ttsPositionCfi: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookCbxProgress {
|
||||||
|
page: number | null;
|
||||||
|
percentage: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookAudiobookProgress {
|
||||||
|
positionMs: number | null;
|
||||||
|
trackIndex: number | null;
|
||||||
|
trackPositionMs: number | null;
|
||||||
|
percentage: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookKoReaderProgress {
|
||||||
|
percentage: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookKoboProgress {
|
||||||
|
percentage: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookSummaryAudiobookMetadata {
|
||||||
|
durationSeconds?: number;
|
||||||
|
bitrate?: number;
|
||||||
|
sampleRate?: number;
|
||||||
|
channels?: number;
|
||||||
|
codec?: string;
|
||||||
|
chapterCount?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookSummaryComicMetadata {
|
||||||
|
pencillers?: string[];
|
||||||
|
inkers?: string[];
|
||||||
|
colorists?: string[];
|
||||||
|
letterers?: string[];
|
||||||
|
coverArtists?: string[];
|
||||||
|
editors?: string[];
|
||||||
|
characters?: string[];
|
||||||
|
teams?: string[];
|
||||||
|
locations?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BookMetadataFields {
|
||||||
|
bookId: number;
|
||||||
|
title?: string;
|
||||||
|
publisher?: string;
|
||||||
|
publishedDate?: string;
|
||||||
|
seriesName?: string;
|
||||||
|
seriesNumber?: number;
|
||||||
|
isbn13?: string;
|
||||||
|
isbn10?: string;
|
||||||
|
pageCount?: number;
|
||||||
|
language?: string;
|
||||||
|
narrator?: string;
|
||||||
|
amazonRating?: number;
|
||||||
|
amazonReviewCount?: number;
|
||||||
|
goodreadsRating?: number;
|
||||||
|
goodreadsReviewCount?: number;
|
||||||
|
hardcoverRating?: number;
|
||||||
|
hardcoverReviewCount?: number;
|
||||||
|
ranobedbRating?: number;
|
||||||
|
coverUpdatedOn?: string;
|
||||||
|
audiobookCoverUpdatedOn?: string;
|
||||||
|
authors?: string[];
|
||||||
|
categories?: string[];
|
||||||
|
moods?: string[];
|
||||||
|
tags?: string[];
|
||||||
|
rating?: number;
|
||||||
|
isFixedLayout?: boolean;
|
||||||
|
ageRating?: number;
|
||||||
|
contentRating?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookSummaryMetadata extends BookMetadataFields {
|
||||||
|
audiobookMetadata?: BookSummaryAudiobookMetadata;
|
||||||
|
comicMetadata?: BookSummaryComicMetadata;
|
||||||
|
allMetadataLocked: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BookRecord<TMetadata extends BookMetadataFields> {
|
||||||
|
id: number;
|
||||||
|
libraryId: number;
|
||||||
|
libraryName: string;
|
||||||
|
primaryFile?: BookFileResponse;
|
||||||
|
lastReadTime?: string;
|
||||||
|
addedOn?: string;
|
||||||
|
metadata?: TMetadata;
|
||||||
|
metadataMatchScore?: number;
|
||||||
|
pdfProgress?: BookPdfProgress;
|
||||||
|
epubProgress?: BookEpubProgress;
|
||||||
|
cbxProgress?: BookCbxProgress;
|
||||||
|
audiobookProgress?: BookAudiobookProgress;
|
||||||
|
koreaderProgress?: BookKoReaderProgress;
|
||||||
|
koboProgress?: BookKoboProgress;
|
||||||
|
personalRating?: number;
|
||||||
|
shelves?: BookShelf[];
|
||||||
|
readStatus?: BookReadStatus;
|
||||||
|
dateFinished?: string;
|
||||||
|
alternativeFormats?: BookFileResponse[];
|
||||||
|
supplementaryFiles?: BookFileResponse[];
|
||||||
|
isPhysical?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BookSummary = BookRecord<BookSummaryMetadata>;
|
||||||
|
|
||||||
|
export interface BookDetailAudiobookChapter {
|
||||||
|
index?: number;
|
||||||
|
title?: string;
|
||||||
|
startTimeMs?: number;
|
||||||
|
endTimeMs?: number;
|
||||||
|
durationMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookDetailAudiobookMetadata extends BookSummaryAudiobookMetadata {
|
||||||
|
chapters?: BookDetailAudiobookChapter[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookDetailComicMetadata extends BookSummaryComicMetadata {
|
||||||
|
issueNumber?: string;
|
||||||
|
volumeName?: string;
|
||||||
|
volumeNumber?: number;
|
||||||
|
storyArc?: string;
|
||||||
|
storyArcNumber?: number;
|
||||||
|
alternateSeries?: string;
|
||||||
|
alternateIssue?: string;
|
||||||
|
imprint?: string;
|
||||||
|
format?: string;
|
||||||
|
blackAndWhite?: boolean;
|
||||||
|
manga?: boolean;
|
||||||
|
readingDirection?: string;
|
||||||
|
webLink?: string;
|
||||||
|
notes?: string;
|
||||||
|
issueNumberLocked?: boolean;
|
||||||
|
volumeNameLocked?: boolean;
|
||||||
|
volumeNumberLocked?: boolean;
|
||||||
|
storyArcLocked?: boolean;
|
||||||
|
storyArcNumberLocked?: boolean;
|
||||||
|
alternateSeriesLocked?: boolean;
|
||||||
|
alternateIssueLocked?: boolean;
|
||||||
|
imprintLocked?: boolean;
|
||||||
|
formatLocked?: boolean;
|
||||||
|
blackAndWhiteLocked?: boolean;
|
||||||
|
mangaLocked?: boolean;
|
||||||
|
readingDirectionLocked?: boolean;
|
||||||
|
webLinkLocked?: boolean;
|
||||||
|
notesLocked?: boolean;
|
||||||
|
creatorsLocked?: boolean;
|
||||||
|
pencillersLocked?: boolean;
|
||||||
|
inkersLocked?: boolean;
|
||||||
|
coloristsLocked?: boolean;
|
||||||
|
letterersLocked?: boolean;
|
||||||
|
coverArtistsLocked?: boolean;
|
||||||
|
editorsLocked?: boolean;
|
||||||
|
charactersLocked?: boolean;
|
||||||
|
teamsLocked?: boolean;
|
||||||
|
locationsLocked?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookDetailMetadata extends BookMetadataFields {
|
||||||
|
subtitle?: string;
|
||||||
|
description?: string;
|
||||||
|
seriesTotal?: number;
|
||||||
|
asin?: string;
|
||||||
|
goodreadsId?: string;
|
||||||
|
comicvineId?: string;
|
||||||
|
hardcoverId?: string;
|
||||||
|
hardcoverBookId?: string;
|
||||||
|
doubanId?: string;
|
||||||
|
googleId?: string;
|
||||||
|
lubimyczytacId?: string;
|
||||||
|
ranobedbId?: string;
|
||||||
|
audibleId?: string;
|
||||||
|
doubanRating?: number;
|
||||||
|
doubanReviewCount?: number;
|
||||||
|
lubimyczytacRating?: number;
|
||||||
|
audibleRating?: number;
|
||||||
|
audibleReviewCount?: number;
|
||||||
|
abridged?: boolean;
|
||||||
|
audiobookMetadata?: BookDetailAudiobookMetadata;
|
||||||
|
comicMetadata?: BookDetailComicMetadata;
|
||||||
|
provider?: BookMetadataProvider;
|
||||||
|
externalUrl?: string;
|
||||||
|
thumbnailUrl?: string;
|
||||||
|
titleLocked?: boolean;
|
||||||
|
subtitleLocked?: boolean;
|
||||||
|
publisherLocked?: boolean;
|
||||||
|
publishedDateLocked?: boolean;
|
||||||
|
descriptionLocked?: boolean;
|
||||||
|
seriesNameLocked?: boolean;
|
||||||
|
seriesNumberLocked?: boolean;
|
||||||
|
seriesTotalLocked?: boolean;
|
||||||
|
isbn13Locked?: boolean;
|
||||||
|
isbn10Locked?: boolean;
|
||||||
|
asinLocked?: boolean;
|
||||||
|
goodreadsIdLocked?: boolean;
|
||||||
|
comicvineIdLocked?: boolean;
|
||||||
|
hardcoverIdLocked?: boolean;
|
||||||
|
hardcoverBookIdLocked?: boolean;
|
||||||
|
doubanIdLocked?: boolean;
|
||||||
|
googleIdLocked?: boolean;
|
||||||
|
pageCountLocked?: boolean;
|
||||||
|
languageLocked?: boolean;
|
||||||
|
amazonRatingLocked?: boolean;
|
||||||
|
amazonReviewCountLocked?: boolean;
|
||||||
|
goodreadsRatingLocked?: boolean;
|
||||||
|
goodreadsReviewCountLocked?: boolean;
|
||||||
|
hardcoverRatingLocked?: boolean;
|
||||||
|
hardcoverReviewCountLocked?: boolean;
|
||||||
|
doubanRatingLocked?: boolean;
|
||||||
|
doubanReviewCountLocked?: boolean;
|
||||||
|
lubimyczytacIdLocked?: boolean;
|
||||||
|
lubimyczytacRatingLocked?: boolean;
|
||||||
|
ranobedbIdLocked?: boolean;
|
||||||
|
ranobedbRatingLocked?: boolean;
|
||||||
|
audibleIdLocked?: boolean;
|
||||||
|
audibleRatingLocked?: boolean;
|
||||||
|
audibleReviewCountLocked?: boolean;
|
||||||
|
externalUrlLocked?: boolean;
|
||||||
|
coverLocked?: boolean;
|
||||||
|
audiobookCoverLocked?: boolean;
|
||||||
|
authorsLocked?: boolean;
|
||||||
|
categoriesLocked?: boolean;
|
||||||
|
moodsLocked?: boolean;
|
||||||
|
tagsLocked?: boolean;
|
||||||
|
reviewsLocked?: boolean;
|
||||||
|
narratorLocked?: boolean;
|
||||||
|
abridgedLocked?: boolean;
|
||||||
|
ageRatingLocked?: boolean;
|
||||||
|
contentRatingLocked?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookDetail extends BookRecord<BookDetailMetadata> {
|
||||||
|
libraryPath?: BookLibraryPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookRecommendation {
|
||||||
|
book: BookDetail;
|
||||||
|
similarityScore: number;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user