Implement clean logout to fully clear app state and tokens

This commit is contained in:
aditya.chandel
2025-08-11 13:30:37 -06:00
committed by Aditya Chandel
parent 964b8e7f67
commit ec5157464a
32 changed files with 638 additions and 425 deletions
@@ -20,9 +20,9 @@
}
</p>
@if (userService.userState$ | async; as userData) {
@if (userService.userState$ | async; as userState) {
@if (entityType !== EntityType.ALL_BOOKS && entityType !== EntityType.UNSHELVED &&
(userData.permissions.admin || userData.permissions.canManipulateLibrary)) {
(userState.user!.permissions.admin || userState.user!.permissions.canManipulateLibrary)) {
<div class="ml-2 flex-shrink-0">
<p-button
icon="pi pi-ellipsis-v"
@@ -286,13 +286,13 @@
}
}
@if (selectedBooks.size > 0) {
@if (userService.userState$ | async; as userData) {
@if (userService.userState$ | async; as userState) {
<div class="book-browser-footer bg-[var(--card-background)] bg-opacity-10" [@slideInOut]>
<div class="flex justify-between items-center">
<div class="flex">
@if (entityType$ | async; as entityType) {
<div class="flex gap-2 md:gap-6 pr-2">
@if (userData.permissions.canEditMetadata) {
@if (userState.user!.permissions.canEditMetadata) {
<p-menu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body" class="hidden"/>
<p-button
(click)="menu.toggle($event)"
@@ -323,7 +323,7 @@
tooltipPosition="top">
</p-button>
}
@if (userData.permissions.canEditMetadata) {
@if (userState.user!.permissions.canEditMetadata) {
<p-button
outlined="true"
icon="pi pi-lock"
@@ -375,7 +375,7 @@
</div>
</div>
@if (userData?.permissions?.admin || userData?.permissions?.canDeleteBook) {
@if (userState?.user?.permissions?.admin || userState?.user?.permissions?.canDeleteBook) {
<p-divider layout="vertical"></p-divider>
<p-button
outlined="true"
@@ -45,7 +45,7 @@ import {MultiSelect} from 'primeng/multiselect';
import {TableColumnPreferenceService} from './table-column-preference-service';
import {TieredMenu} from 'primeng/tieredmenu';
import {BookMenuService} from '../../service/book-menu.service';
import {MagicShelf, MagicShelfService} from '../../../magic-shelf-service';
import {MagicShelf, MagicShelfService} from '../../../magic-shelf.service';
import {BookRuleEvaluatorService} from '../../../book-rule-evaluator.service';
import {GroupRule} from '../../../magic-shelf-component/magic-shelf-component';
@@ -136,7 +136,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
rawFilterParamFromUrl: string | null = null;
hasSearchTerm = false;
visibleColumns: { field: string; header: string }[] = [];
entityViewPreferences!: EntityViewPreferences;
entityViewPreferences: EntityViewPreferences | undefined;
currentViewMode: string | undefined;
lastAppliedSort: SortOption | null = null;
private settingFiltersFromUrl = false;
@@ -161,7 +161,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
ngOnInit(): void {
this.coverScalePreferenceService.scaleChange$.pipe(debounceTime(1000)).subscribe();
this.bookService.loadBooks();
const currentPath = this.activatedRoute.snapshot.routeConfig?.path;
if (currentPath === 'all-books' || currentPath === 'unshelved-books') {
@@ -206,7 +205,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
combineLatest({
paramMap: this.activatedRoute.queryParamMap,
user: this.userService.userState$.pipe(
filter((user): user is NonNullable<typeof user> => !!user),
filter(userState => !!userState?.user && userState.loaded),
take(1)
)
}).subscribe(({paramMap, user}) => {
@@ -250,12 +249,12 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.currentFilterLabel = 'All Books';
}
this.entityViewPreferences = user.userSettings?.entityViewPreferences;
this.entityViewPreferences = user.user?.userSettings?.entityViewPreferences;
const globalPrefs = this.entityViewPreferences?.global;
const currentEntityTypeStr = this.entityType ? this.entityType.toString().toUpperCase() : undefined;
this.coverScalePreferenceService.initScaleValue(this.coverScalePreferenceService.scaleFactor);
this.filterSortPreferenceService.initValue(user?.userSettings?.filterSortingMode);
this.columnPreferenceService.initPreferences(user.userSettings?.tableColumnPreference);
this.filterSortPreferenceService.initValue(user.user?.userSettings?.filterSortingMode);
this.columnPreferenceService.initPreferences(user.user?.userSettings?.tableColumnPreference);
this.visibleColumns = this.columnPreferenceService.visibleColumns;
@@ -67,12 +67,12 @@ export class BookCardComponent implements OnInit, OnDestroy {
ngOnInit(): void {
this.userService.userState$
.pipe(
filter(user => !!user),
filter(userState => !!userState),
takeUntil(this.destroy$)
)
.subscribe(user => {
this.userPermissions = user.permissions;
this.metadataCenterViewMode = user?.userSettings.metadataCenterViewMode ?? 'route';
.subscribe(userState => {
this.userPermissions = userState.user?.permissions;
this.metadataCenterViewMode = userState?.user?.userSettings.metadataCenterViewMode ?? 'route';
this.initMenu();
});
}
@@ -13,7 +13,7 @@ import {FormsModule} from '@angular/forms';
import {SelectButton} from 'primeng/selectbutton';
import {UserService} from '../../../../settings/user-management/user.service';
import {FilterSortPreferenceService} from '../filters/filter-sorting-preferences.service';
import {MagicShelf} from '../../../../magic-shelf-service';
import {MagicShelf} from '../../../../magic-shelf.service';
import {GroupRule} from '../../../../magic-shelf-component/magic-shelf-component';
import {BookRuleEvaluatorService} from '../../../../book-rule-evaluator.service';
@@ -75,11 +75,11 @@ export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
ngOnInit(): void {
this.userService.userState$
.pipe(
filter(user => !!user),
filter(userState => !!userState),
takeUntil(this.destroy$)
)
.subscribe(user => {
this.metadataCenterViewMode = user?.userSettings.metadataCenterViewMode ?? 'route';
.subscribe(userState => {
this.metadataCenterViewMode = userState?.user?.userSettings.metadataCenterViewMode ?? 'route';
});
this.setScrollHeight();
@@ -1,27 +1,31 @@
import {BookFilter} from './BookFilter';
import {Observable, BehaviorSubject} from 'rxjs';
import {BehaviorSubject, Observable, Subject} from 'rxjs';
import {BookState} from '../../../model/state/book-state.model';
import {map, debounceTime, filter, take} from 'rxjs/operators';
import {debounceTime, filter, map, takeUntil} from 'rxjs/operators';
import {Book} from '../../../model/book.model';
import {inject, Injectable} from '@angular/core';
import {inject, Injectable, OnDestroy} from '@angular/core';
import {MessageService} from 'primeng/api';
import {UserService} from '../../../../settings/user-management/user.service';
@Injectable({providedIn: 'root'})
export class SeriesCollapseFilter implements BookFilter {
export class SeriesCollapseFilter implements BookFilter, OnDestroy {
private readonly userService = inject(UserService);
private readonly messageService = inject(MessageService);
private readonly seriesCollapseSubject = new BehaviorSubject<boolean>(false);
readonly seriesCollapse$ = this.seriesCollapseSubject.asObservable();
private destroy$ = new Subject<void>();
private hasUserToggled = false;
constructor() {
this.userService.userState$
.pipe(filter(user => !!user), take(1))
.pipe(
filter(userState => !!userState),
takeUntil(this.destroy$)
)
.subscribe(user => {
const prefs = user.userSettings?.entityViewPreferences;
const prefs = user.user?.userSettings?.entityViewPreferences;
const initialCollapsed = prefs?.global?.seriesCollapsed ?? false;
this.seriesCollapseSubject.next(initialCollapsed);
});
@@ -102,4 +106,9 @@ export class SeriesCollapseFilter implements BookFilter {
life: 1500
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}
@@ -1,17 +1,13 @@
import {Component, inject, Input, OnInit} from '@angular/core';
import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
import {Book} from '../../model/book.model';
import {UrlHelperService} from '../../../utilities/service/url-helper.service';
import {Button} from 'primeng/button';
import {BookMetadataCenterComponent} from '../../../metadata/book-metadata-center-component/book-metadata-center.component';
import {BookService} from '../../service/book.service';
import {DialogService} from 'primeng/dynamicdialog';
import {UserService} from '../../../settings/user-management/user.service';
import {EmailService} from '../../../settings/email/email.service';
import {ConfirmationService, MessageService} from 'primeng/api';
import {Router} from '@angular/router';
import {filter} from 'rxjs';
import {filter, Subject} from 'rxjs';
import {NgClass} from '@angular/common';
import {BookMetadataHostService} from '../../../utilities/service/book-metadata-host-service';
import {takeUntil} from 'rxjs/operators';
@Component({
selector: 'app-book-card-lite-component',
@@ -22,7 +18,7 @@ import {BookMetadataHostService} from '../../../utilities/service/book-metadata-
templateUrl: './book-card-lite-component.html',
styleUrl: './book-card-lite-component.scss'
})
export class BookCardLiteComponent implements OnInit {
export class BookCardLiteComponent implements OnInit, OnDestroy {
@Input() book!: Book;
private router = inject(Router);
@@ -30,14 +26,19 @@ export class BookCardLiteComponent implements OnInit {
private userService = inject(UserService);
private bookMetadataHostService = inject(BookMetadataHostService);
private destroy$ = new Subject<void>();
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
isHovered: boolean = false;
ngOnInit(): void {
this.userService.userState$
.pipe(filter(user => !!user))
.pipe(
filter(userState => !!userState),
takeUntil(this.destroy$)
)
.subscribe((user) => {
this.metadataCenterViewMode = user?.userSettings.metadataCenterViewMode ?? 'route';
this.metadataCenterViewMode = user?.user?.userSettings.metadataCenterViewMode ?? 'route';
});
}
@@ -50,4 +51,9 @@ export class BookCardLiteComponent implements OnInit {
this.bookMetadataHostService.requestBookSwitch(book.id);
}
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}
@@ -1,7 +1,7 @@
import {inject, Injectable} from '@angular/core';
import {BehaviorSubject, first, Observable, of, throwError} from 'rxjs';
import {HttpClient, HttpParams} from '@angular/common/http';
import {catchError, filter, map, tap} from 'rxjs/operators';
import {catchError, filter, map, tap, shareReplay, finalize, distinctUntilChanged} from 'rxjs/operators';
import {Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BulkMetadataUpdateRequest, MetadataUpdateWrapper, ReadStatus} from '../model/book.model';
import {BookState} from '../model/state/book-state.model';
import {API_CONFIG} from '../../config/api-config';
@@ -9,6 +9,7 @@ import {FetchMetadataRequest} from '../../metadata/model/request/fetch-metadata-
import {MetadataRefreshRequest} from '../../metadata/model/request/metadata-refresh-request.model';
import {MessageService} from 'primeng/api';
import {ResetProgressType, ResetProgressTypes} from '../../shared/constants/reset-progress-type';
import {AuthService} from '../../core/service/auth.service';
@Injectable({
providedIn: 'root',
@@ -17,22 +18,57 @@ export class BookService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
private http = inject(HttpClient);
private messageService = inject(MessageService);
private authService = inject(AuthService);
private bookStateSubject = new BehaviorSubject<BookState>({
books: null,
loaded: false,
error: null,
});
bookState$ = this.bookStateSubject.asObservable();
private http = inject(HttpClient);
private messageService = inject(MessageService);
private loading$: Observable<Book[]> | null = null;
loadBooks(): void {
const currentState = this.bookStateSubject.value;
if (currentState.loaded && this.bookStateSubject.value.books != null) {
return;
}
this.http.get<Book[]>(this.url).pipe(
constructor() {
this.authService.token$.pipe(
distinctUntilChanged()
).subscribe(token => {
if (token === null) {
this.bookStateSubject.next({
books: null,
loaded: true,
error: null,
});
this.loading$ = null;
} else {
const current = this.bookStateSubject.value;
if (current.loaded && !current.books) {
this.bookStateSubject.next({
books: null,
loaded: false,
error: null,
});
this.loading$ = null;
}
}
});
}
bookState$ = this.bookStateSubject.asObservable().pipe(
tap(state => {
if (!state.loaded && !state.error && !this.loading$) {
this.loading$ = this.fetchBooks().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
private fetchBooks(): Observable<Book[]> {
return this.http.get<Book[]>(this.url).pipe(
tap(books => {
this.bookStateSubject.next({
books: books || [],
@@ -41,14 +77,15 @@ export class BookService {
});
}),
catchError(error => {
const curr = this.bookStateSubject.value;
this.bookStateSubject.next({
books: null,
books: curr.books,
loaded: true,
error: error.message,
});
return of(null);
throw error;
})
).subscribe();
);
}
getBookByIdFromState(bookId: number): Book | undefined {
@@ -10,7 +10,7 @@ import {MetadataFetchOptionsComponent} from '../../metadata/metadata-options-dia
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
import {LibraryCreatorComponent} from '../components/library-creator/library-creator.component';
import {ShelfEditDialogComponent} from '../components/shelf-edit-dialog/shelf-edit-dialog.component';
import {MagicShelf, MagicShelfService} from '../../magic-shelf-service';
import {MagicShelf, MagicShelfService} from '../../magic-shelf.service';
import {MagicShelfComponent} from '../../magic-shelf-component/magic-shelf-component';
@Injectable({
@@ -1,119 +1,145 @@
import {inject, Injectable} from '@angular/core';
import {BehaviorSubject, Observable, of, tap} from 'rxjs';
import {HttpClient} from '@angular/common/http';
import {catchError, map} from 'rxjs/operators';
import {Library} from '../model/library.model';
import {BookService} from './book.service';
import {LibraryState} from '../model/state/library-state.model';
import {API_CONFIG} from '../../config/api-config';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {catchError, distinctUntilChanged, finalize, map, shareReplay, tap} from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
import {Library} from '../model/library.model';
import {LibraryState} from '../model/state/library-state.model';
import {BookService} from './book.service';
import {API_CONFIG} from '../../config/api-config';
import {AuthService} from '../../core/service/auth.service';
@Injectable({providedIn: 'root'})
export class LibraryService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries`;
private http = inject(HttpClient);
private bookService = inject(BookService);
private authService = inject(AuthService);
private libraryStateSubject = new BehaviorSubject<LibraryState>({
libraries: null,
loaded: false,
error: null,
});
libraryState$ = this.libraryStateSubject.asObservable();
private http = inject(HttpClient);
private bookService = inject(BookService);
private loading$: Observable<Library[]> | null = null;
constructor() {
this.loadLibraries();
}
private loadLibraries(): void {
this.http.get<Library[]>(this.url).pipe(
catchError(error => {
this.authService.token$.pipe(
distinctUntilChanged()
).subscribe(token => {
if (token === null) {
this.libraryStateSubject.next({
libraries: null,
loaded: true,
error: error.message,
error: null,
});
return of([]);
})
).subscribe(libraries => {
this.libraryStateSubject.next({
libraries,
loaded: true,
error: null,
});
this.loading$ = null;
} else {
const current = this.libraryStateSubject.value;
if (current.loaded && !current.libraries) {
this.libraryStateSubject.next({
libraries: null,
loaded: false,
error: null,
});
this.loading$ = null;
}
}
});
}
doesLibraryExistByName(name: string): boolean {
const libraries = this.libraryStateSubject.value.libraries || [];
return libraries.some(library => library.name === name);
}
libraryState$ = this.libraryStateSubject.asObservable().pipe(
tap(state => {
if (!state.loaded && !state.error && !this.loading$) {
this.loading$ = this.fetchLibraries().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
findLibraryById(id: number): Library | undefined {
return this.libraryStateSubject.value.libraries?.find(library => library.id === id);
}
createLibrary(newLibrary: Library): Observable<Library> {
return this.http.post<Library>(this.url, newLibrary).pipe(
map(createdLibrary => {
const currentState = this.libraryStateSubject.value;
const updatedLibraries = currentState.libraries ? [...currentState.libraries, createdLibrary] : [createdLibrary];
this.libraryStateSubject.next({...currentState, libraries: updatedLibraries});
return createdLibrary;
}),
catchError(error => {
throw error;
private fetchLibraries(): Observable<Library[]> {
return this.http.get<Library[]>(this.url).pipe(
tap(libs => this.libraryStateSubject.next({libraries: libs, loaded: true, error: null})),
catchError(err => {
const current = this.libraryStateSubject.value;
this.libraryStateSubject.next({libraries: current.libraries, loaded: true, error: err.message});
throw err;
})
);
}
updateLibrary(library: Library, libraryId: number | undefined): Observable<Library> {
return this.http.put<Library>(`${this.url}/${libraryId}`, library).pipe(
map(updatedLibrary => {
const currentState = this.libraryStateSubject.value;
const updatedLibraries = currentState.libraries ? currentState.libraries.map(existingLibrary =>
existingLibrary.id === updatedLibrary.id ? updatedLibrary : existingLibrary) : [updatedLibrary];
this.libraryStateSubject.next({...currentState, libraries: updatedLibraries,});
return updatedLibrary;
}),
catchError(error => {
throw error;
createLibrary(lib: Library): Observable<Library> {
return this.http.post<Library>(this.url, lib).pipe(
map(created => {
const curr = this.libraryStateSubject.value;
const updated = curr.libraries ? [...curr.libraries, created] : [created];
this.libraryStateSubject.next({...curr, libraries: updated});
return created;
})
);
}
deleteLibrary(libraryId: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${libraryId}`).pipe(
updateLibrary(lib: Library, id?: number): Observable<Library> {
return this.http.put<Library>(`${this.url}/${id}`, lib).pipe(
map(updated => {
const curr = this.libraryStateSubject.value;
const list = curr.libraries?.map(l => (l.id === updated.id ? updated : l)) || [updated];
this.libraryStateSubject.next({...curr, libraries: list});
return updated;
})
);
}
deleteLibrary(id: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${id}`).pipe(
tap(() => {
this.bookService.removeBooksByLibraryId(libraryId);
const currentState = this.libraryStateSubject.value;
const updatedLibraries = currentState.libraries?.filter(library => library.id !== libraryId) || [];
this.libraryStateSubject.next({...currentState, libraries: updatedLibraries});
this.bookService.removeBooksByLibraryId(id);
const curr = this.libraryStateSubject.value;
const filtered = curr.libraries?.filter(l => l.id !== id) || [];
this.libraryStateSubject.next({...curr, libraries: filtered});
}),
catchError(error => {
const currentState = this.libraryStateSubject.value;
this.libraryStateSubject.next({...currentState, error: error.message});
catchError(err => {
const curr = this.libraryStateSubject.value;
this.libraryStateSubject.next({...curr, error: err.message});
return of();
})
);
}
refreshLibrary(libraryId: number): Observable<void> {
return this.http.put<void>(`${this.url}/${libraryId}/refresh`, {}).pipe(
catchError(error => {
const currentState = this.libraryStateSubject.value;
this.libraryStateSubject.next({...currentState, error: error.message});
throw error;
refreshLibrary(id: number): Observable<void> {
return this.http.put<void>(`${this.url}/${id}/refresh`, {}).pipe(
catchError(err => {
const curr = this.libraryStateSubject.value;
this.libraryStateSubject.next({...curr, error: err.message});
throw err;
})
);
}
getBookCount(libraryId: number): Observable<number> {
return this.bookService.bookState$.pipe(
map(state => (state.books || []).filter(book => book.libraryId === libraryId).length)
);
updateLibraryFileNamingPattern(id: number, pattern: string): Observable<Library> {
return this.http
.patch<Library>(`${this.url}/${id}/file-naming-pattern`, {fileNamingPattern: pattern})
.pipe(
map(updated => {
const curr = this.libraryStateSubject.value;
const list = curr.libraries?.map(l => (l.id === updated.id ? updated : l)) || [updated];
this.libraryStateSubject.next({...curr, libraries: list});
return updated;
})
);
}
doesLibraryExistByName(name: string): boolean {
return (this.libraryStateSubject.value.libraries || []).some(l => l.name === name);
}
findLibraryById(id: number): Library | undefined {
return this.libraryStateSubject.value.libraries?.find(l => l.id === id);
}
getLibrariesFromState(): Library[] {
@@ -121,28 +147,14 @@ export class LibraryService {
}
getLibraryPathById(pathId: number): string | undefined {
const libraries = this.libraryStateSubject.value.libraries || [];
for (const library of libraries) {
const match = library.paths.find(p => p.id === pathId);
if (match) {
return match.path;
}
}
return undefined;
return this.libraryStateSubject.value.libraries
?.find(lib => lib.paths.some(p => p.id === pathId))
?.paths.find(p => p.id === pathId)?.path;
}
updateLibraryFileNamingPattern(libraryId: number, fileNamingPattern: string): Observable<Library> {
return this.http.patch<Library>(`${this.url}/${libraryId}/file-naming-pattern`, { fileNamingPattern }).pipe(
map(updatedLibrary => {
const currentState = this.libraryStateSubject.value;
const updatedLibraries = currentState.libraries ? currentState.libraries.map(existingLibrary =>
existingLibrary.id === updatedLibrary.id ? updatedLibrary : existingLibrary) : [updatedLibrary];
this.libraryStateSubject.next({...currentState, libraries: updatedLibraries});
return updatedLibrary;
}),
catchError(error => {
throw error;
})
getBookCount(libraryId: number): Observable<number> {
return this.bookService.bookState$.pipe(
map(state => (state.books || []).filter(b => b.libraryId === libraryId).length)
);
}
}
@@ -1,108 +1,96 @@
import {inject, Injectable} from '@angular/core';
import { BehaviorSubject, Observable, of, tap } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Shelf } from '../model/shelf.model';
import { SortOption } from '../model/sort.model';
import { BookService } from './book.service';
import { ShelfState } from '../model/state/shelf-state.model';
import {API_CONFIG} from '../../config/api-config';
import {Library} from '../model/library.model';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { tap, catchError, map, shareReplay, finalize } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
import { Shelf } from '../model/shelf.model';
import { ShelfState } from '../model/state/shelf-state.model';
import { BookService } from './book.service';
import { API_CONFIG } from '../../config/api-config';
@Injectable({ providedIn: 'root' })
export class ShelfService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/shelves`;
private http = inject(HttpClient);
private bookService = inject(BookService);
private shelfStateSubject = new BehaviorSubject<ShelfState>({
shelves: null,
loaded: false,
error: null,
});
shelfState$ = this.shelfStateSubject.asObservable();
private http = inject(HttpClient);
private bookService = inject(BookService);
private loading$: Observable<Shelf[]> | null = null;
constructor() {
this.loadShelves();
}
shelfState$ = this.shelfStateSubject.asObservable().pipe(
tap(state => {
if (!state.loaded && !state.error && !this.loading$) {
this.loading$ = this.fetchShelves().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
private loadShelves(): void {
this.http.get<Shelf[]>(this.url).pipe(
catchError(error => {
this.shelfStateSubject.next({
shelves: null,
loaded: true,
error: error.message,
});
return of([]);
private fetchShelves(): Observable<Shelf[]> {
return this.http.get<Shelf[]>(this.url).pipe(
tap(shelves => this.shelfStateSubject.next({ shelves, loaded: true, error: null })),
catchError(err => {
const curr = this.shelfStateSubject.value;
this.shelfStateSubject.next({ shelves: curr.shelves, loaded: true, error: err.message });
throw err;
})
).subscribe(shelves => {
this.shelfStateSubject.next({
shelves,
loaded: true,
error: null,
});
});
}
getShelfById(shelfId: number): Shelf | undefined {
let shelfState = this.shelfStateSubject.value;
return shelfState.shelves?.find(shelf => shelf.id === shelfId);
);
}
createShelf(shelf: Shelf): Observable<Shelf> {
return this.http.post<Shelf>(this.url, shelf).pipe(
map(newShelf => {
const currentState = this.shelfStateSubject.value;
const updatedShelves = currentState.shelves ? [...currentState.shelves, newShelf] : [newShelf];
this.shelfStateSubject.next({ ...currentState, shelves: updatedShelves });
const curr = this.shelfStateSubject.value;
const updated = curr.shelves ? [...curr.shelves, newShelf] : [newShelf];
this.shelfStateSubject.next({ ...curr, shelves: updated });
return newShelf;
}),
catchError(error => {
const currentState = this.shelfStateSubject.value;
this.shelfStateSubject.next({ ...currentState, error: error.message });
throw error;
})
);
}
updateShelf(shelf: Shelf, shelfId: number | undefined): Observable<Shelf> {
return this.http.put<Shelf>(`${this.url}/${shelfId}`, shelf).pipe(
map(updatedShelf => {
const currentState = this.shelfStateSubject.value;
const updatedShelves = currentState.shelves ? currentState.shelves.map(existingShelf =>
existingShelf.id === updatedShelf.id ? updatedShelf : existingShelf) : [updatedShelf];
this.shelfStateSubject.next({...currentState, shelves: updatedShelves,});
return updatedShelf;
}),
catchError(error => {
throw error;
updateShelf(shelf: Shelf, id?: number): Observable<Shelf> {
return this.http.put<Shelf>(`${this.url}/${id}`, shelf).pipe(
map(updated => {
const curr = this.shelfStateSubject.value;
const list = curr.shelves?.map(s => (s.id === updated.id ? updated : s)) || [updated];
this.shelfStateSubject.next({ ...curr, shelves: list });
return updated;
})
);
}
deleteShelf(shelfId: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${shelfId}`).pipe(
deleteShelf(id: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${id}`).pipe(
tap(() => {
this.bookService.removeBooksFromShelf(shelfId);
const currentState = this.shelfStateSubject.value;
const updatedShelves = currentState.shelves?.filter(shelf => shelf.id !== shelfId) || [];
this.shelfStateSubject.next({ ...currentState, shelves: updatedShelves });
this.bookService.removeBooksFromShelf(id);
const curr = this.shelfStateSubject.value;
const filtered = curr.shelves?.filter(s => s.id !== id) || [];
this.shelfStateSubject.next({ ...curr, shelves: filtered });
}),
catchError(error => {
const currentState = this.shelfStateSubject.value;
this.shelfStateSubject.next({ ...currentState, error: error.message });
catchError(err => {
const curr = this.shelfStateSubject.value;
this.shelfStateSubject.next({ ...curr, error: err.message });
return of();
})
);
}
getShelfById(id: number): Shelf | undefined {
return this.shelfStateSubject.value.shelves?.find(s => s.id === id);
}
getBookCount(shelfId: number): Observable<number> {
return this.bookService.bookState$.pipe(
map(state =>
(state.books || []).filter(book => book.shelves?.some(shelf => shelf.id === shelfId)).length
(state.books || []).filter(b => b.shelves?.some(s => s.id === shelfId)).length
)
);
}
@@ -110,7 +98,7 @@ export class ShelfService {
getUnshelvedBookCount(): Observable<number> {
return this.bookService.bookState$.pipe(
map(state =>
(state.books || []).filter(book => !book.shelves || book.shelves.length === 0).length
(state.books || []).filter(b => !b.shelves || b.shelves.length === 0).length
)
);
}