Files
grimmory/booklore-ui/src/app/features/magic-shelf/service/magic-shelf.service.ts
T
Balázs Szücs ab96eee5bc refactor(types): replace most usages of 'any' with 'unknown' and improve type safety across services and components (#2050)
* refactor(types): replace most usages of 'any' with 'unknown' and improve type safety across services and components

- Update method signatures, variables, and interfaces to use 'unknown' instead of 'any'
- Refine event and observable typings for better type inference
- Add or adjust explicit types for function parameters and return values
- Update Chart.js tooltip and context typings for chart services
- Improve type safety in Book, BookState, and related models
- Adjust template bindings and method calls to match stricter typings
- Add SecureSrcDirective for secure image loading with fallback and error handling

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* chore(angular): remove proxy configuration from development build settings

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* refactor(book-browser): streamline entity and book state management with reactive streams

- Refactor entity type and entity fetching logic to use observables and combine route params
- Simplify book state handling by consolidating filtering and fetching into a single reactive pipeline
- Remove redundant applySortOption logic and related subscriptions
- Fix book card index binding in template for improved rendering performance
- Ensure proper cleanup of epub rendition in epub-reader component

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* fix(book-browser, book-uploader): improve permission checks and enhance file upload handling

- Use optional chaining for user permission checks in book-browser.component.html to prevent runtime errors when user data is undefined
- Refactor book-uploader.component.ts to pass destination and IDs explicitly to uploadBatch, reconstruct files for strict type handling, and ensure proper upload flow and UI feedback

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* refactor(charts, services): improve type safety for book state validation and update form field checks

- Refactor isValidBookState methods across chart components and services to use type predicates and stricter type checks for BookState
- Update metadata-picker.component to simplify array field checks for authors, categories, moods, and tags
- Adjust magic-shelf-utils to remove unnecessary fallback in object spread
- Update notification-event.service to use correct timeout type for highlightTimeout

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* fix(theme): ensure safe merging of theme properties and improve type definition for themesMap

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* refactor(epub-reader): streamline book and rendition initialization logic

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

---------

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
2026-01-02 18:22:54 -07:00

175 lines
5.1 KiB
TypeScript

import {inject, Injectable} from '@angular/core';
import {API_CONFIG} from '../../../core/config/api-config';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {catchError, distinctUntilChanged, finalize, map, shareReplay, switchMap, tap} from 'rxjs/operators';
import {BookService} from '../../book/service/book.service';
import {BookRuleEvaluatorService} from './book-rule-evaluator.service';
import {AuthService} from '../../../shared/service/auth.service';
import {GroupRule} from '../component/magic-shelf-component';
export interface MagicShelf {
id?: number | null;
name: string;
icon?: string;
iconType?: 'PRIME_NG' | 'CUSTOM_SVG';
filterJson: string;
isPublic?: boolean;
}
export interface MagicShelfState {
shelves: MagicShelf[] | null;
loaded: boolean;
error: string | null;
}
@Injectable({
providedIn: 'root',
})
export class MagicShelfService {
private readonly url = `${API_CONFIG.BASE_URL}/api/magic-shelves`;
private readonly http = inject(HttpClient);
private readonly bookService = inject(BookService);
private readonly ruleEvaluatorService = inject(BookRuleEvaluatorService);
private readonly authService = inject(AuthService);
private readonly shelvesStateSubject = new BehaviorSubject<MagicShelfState>({
shelves: null,
loaded: false,
error: null,
});
private loading$: Observable<MagicShelf[]> | null = null;
constructor() {
this.authService.token$.pipe(
distinctUntilChanged()
).subscribe(token => {
if (token === null) {
this.shelvesStateSubject.next({
shelves: null,
loaded: true,
error: null,
});
this.loading$ = null;
} else {
const current = this.shelvesStateSubject.value;
if (current.loaded && !current.shelves) {
this.shelvesStateSubject.next({
shelves: null,
loaded: false,
error: null,
});
this.loading$ = null;
}
}
});
}
public readonly shelvesState$ = this.shelvesStateSubject.asObservable().pipe(
tap(state => {
if (!state.loaded && !state.error && !this.loading$) {
this.loading$ = this.fetchMagicShelves().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
private get state(): MagicShelfState {
return this.shelvesStateSubject.value;
}
private fetchMagicShelves(): Observable<MagicShelf[]> {
return this.http.get<MagicShelf[]>(this.url).pipe(
tap(shelves => this.shelvesStateSubject.next({shelves, loaded: true, error: null})),
catchError(err => {
const curr = this.shelvesStateSubject.value;
this.shelvesStateSubject.next({shelves: curr.shelves, loaded: true, error: err.message});
throw err;
})
);
}
saveShelf(data: { id?: number; name: string | null; icon: string | null; iconType?: 'PRIME_NG' | 'CUSTOM_SVG'; group: unknown, isPublic?: boolean | null }): Observable<MagicShelf> {
const payload: MagicShelf = {
id: data.id,
name: data.name ?? '',
icon: data.icon ?? 'pi pi-book',
iconType: data.iconType,
filterJson: JSON.stringify(data.group),
isPublic: data.isPublic ?? false
};
return this.http.post<MagicShelf>(this.url, payload).pipe(
tap((newShelf) => {
const curr = this.state;
const shelves = curr.shelves || [];
const updated = shelves.some((s) => s.id === newShelf.id)
? shelves.map((s) => (s.id === newShelf.id ? newShelf : s))
: [...shelves, newShelf];
this.shelvesStateSubject.next({...curr, shelves: updated});
}),
catchError((error) => {
this.updateError(error.message);
throw error;
})
);
}
getShelf(id: number): Observable<MagicShelf | undefined> {
return this.shelvesState$.pipe(
map(state => (state.shelves || []).find(shelf => shelf.id === id))
);
}
deleteShelf(id: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${id}`).pipe(
tap(() => {
const curr = this.state;
const updated = (curr.shelves || []).filter((s) => s.id !== id);
this.shelvesStateSubject.next({...curr, shelves: updated});
}),
catchError((error) => {
this.updateError(error.message);
throw error;
})
);
}
private updateError(error: string): void {
this.shelvesStateSubject.next({
...this.state,
error,
loaded: true,
});
}
getBookCount(shelfId: number): Observable<number> {
return this.getShelf(shelfId).pipe(
switchMap((shelf) => {
if (!shelf) return of(0);
let group: GroupRule;
try {
group = JSON.parse(shelf.filterJson);
} catch (e) {
console.error('Invalid filter JSON', e);
return of(0);
}
return this.bookService.bookState$.pipe(
map((state) =>
(state.books ?? []).filter((book) =>
this.ruleEvaluatorService.evaluateGroup(book, group)
).length
)
);
})
);
}
}